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 if (ricName == null) {
99 Collection<PolicyType> types = this.policyTypes.getAll();
100 return new ResponseEntity<>(toPolicyTypeSchemasJson(types), HttpStatus.OK);
103 Collection<PolicyType> types = rics.getRic(ricName).getSupportedPolicyTypes();
104 return new ResponseEntity<>(toPolicyTypeSchemasJson(types), HttpStatus.OK);
105 } catch (ServiceException e) {
106 return new ResponseEntity<>(e.toString(), HttpStatus.NOT_FOUND);
111 @GetMapping("/policy_schema")
112 @ApiOperation(value = "Returns one policy type schema definition")
115 @ApiResponse(code = 200, message = "Policy schema", response = Object.class),
116 @ApiResponse(code = 404, message = "RIC is not found", response = String.class)})
117 public ResponseEntity<String> getPolicySchema(@RequestParam(name = "id", required = true) String id) {
119 PolicyType type = policyTypes.getType(id);
120 return new ResponseEntity<>(type.schema(), HttpStatus.OK);
121 } catch (ServiceException e) {
122 return new ResponseEntity<>(e.toString(), HttpStatus.NOT_FOUND);
126 @GetMapping("/policy_types")
127 @ApiOperation(value = "Query policy type names")
132 message = "Policy type names",
133 response = String.class,
134 responseContainer = "List"),
135 @ApiResponse(code = 404, message = "RIC is not found", response = String.class)})
136 public ResponseEntity<String> getPolicyTypes(@RequestParam(name = "ric", required = false) String ricName) {
137 if (ricName == null) {
138 Collection<PolicyType> types = this.policyTypes.getAll();
139 return new ResponseEntity<>(toPolicyTypeIdsJson(types), HttpStatus.OK);
142 Collection<PolicyType> types = rics.getRic(ricName).getSupportedPolicyTypes();
143 return new ResponseEntity<>(toPolicyTypeIdsJson(types), HttpStatus.OK);
144 } catch (ServiceException e) {
145 return new ResponseEntity<>(e.toString(), HttpStatus.NOT_FOUND);
150 @GetMapping("/policy")
151 @ApiOperation(value = "Returns a policy configuration") //
154 @ApiResponse(code = 200, message = "Policy found", response = Object.class), //
155 @ApiResponse(code = 404, message = "Policy is not found")} //
157 public ResponseEntity<String> getPolicy( //
158 @RequestParam(name = "id", required = true) String id) {
160 Policy p = policies.getPolicy(id);
161 return new ResponseEntity<>(p.json(), HttpStatus.OK);
162 } catch (ServiceException e) {
163 return new ResponseEntity<>(e.getMessage(), HttpStatus.NOT_FOUND);
167 @DeleteMapping("/policy")
168 @ApiOperation(value = "Delete a policy", response = Object.class)
171 @ApiResponse(code = 204, message = "Policy deleted", response = Object.class),
172 @ApiResponse(code = 404, message = "Policy is not found", response = String.class),
173 @ApiResponse(code = 423, message = "RIC is not operational", response = String.class)})
174 public Mono<ResponseEntity<Object>> deletePolicy( //
175 @RequestParam(name = "id", required = true) String id) {
177 Policy policy = policies.getPolicy(id);
178 keepServiceAlive(policy.ownerServiceName());
179 Ric ric = policy.ric();
180 return ric.getLock().lock(LockType.SHARED) //
181 .flatMap(notUsed -> assertRicStateIdle(ric)) //
182 .flatMap(notUsed -> a1ClientFactory.createA1Client(policy.ric())) //
183 .doOnNext(notUsed -> policies.remove(policy)) //
184 .flatMap(client -> client.deletePolicy(policy)) //
185 .doOnNext(notUsed -> ric.getLock().unlockBlocking()) //
186 .doOnError(notUsed -> ric.getLock().unlockBlocking()) //
187 .flatMap(notUsed -> Mono.just(new ResponseEntity<>(HttpStatus.NO_CONTENT)))
188 .onErrorResume(this::handleException);
189 } catch (ServiceException e) {
190 return Mono.just(new ResponseEntity<>(HttpStatus.NOT_FOUND));
194 @PutMapping(path = "/policy")
195 @ApiOperation(value = "Put a policy", response = String.class)
198 @ApiResponse(code = 201, message = "Policy created", response = Object.class), //
199 @ApiResponse(code = 200, message = "Policy updated", response = Object.class), //
200 @ApiResponse(code = 423, message = "RIC is not operational", response = String.class), //
201 @ApiResponse(code = 404, message = "RIC or policy type is not found", response = String.class) //
203 public Mono<ResponseEntity<Object>> putPolicy( //
204 @RequestParam(name = "type", required = false, defaultValue = "") String typeName, //
205 @RequestParam(name = "id", required = true) String instanceId, //
206 @RequestParam(name = "ric", required = true) String ricName, //
207 @RequestParam(name = "service", required = true) String service, //
208 @RequestBody Object jsonBody) {
210 String jsonString = gson.toJson(jsonBody);
211 Ric ric = rics.get(ricName);
212 PolicyType type = policyTypes.get(typeName);
213 keepServiceAlive(service);
214 if (ric == null || type == null) {
215 return Mono.just(new ResponseEntity<>(HttpStatus.NOT_FOUND));
217 Policy policy = ImmutablePolicy.builder() //
222 .ownerServiceName(service) //
223 .lastModified(getTimeStampUtc()) //
226 final boolean isCreate = this.policies.get(policy.id()) == null;
228 return ric.getLock().lock(LockType.SHARED) //
229 .flatMap(p -> assertRicStateIdle(ric)) //
230 .flatMap(p -> validateModifiedPolicy(policy)) //
231 .flatMap(notUsed -> a1ClientFactory.createA1Client(ric)) //
232 .flatMap(client -> client.putPolicy(policy)) //
233 .doOnNext(notUsed -> policies.put(policy)) //
234 .doOnNext(notUsed -> ric.getLock().unlockBlocking()) //
235 .doOnError(t -> ric.getLock().unlockBlocking()) //
236 .flatMap(notUsed -> Mono.just(new ResponseEntity<>(isCreate ? HttpStatus.CREATED : HttpStatus.OK))) //
237 .onErrorResume(this::handleException);
240 @SuppressWarnings({"unchecked"})
241 private <T> Mono<ResponseEntity<T>> createResponseEntity(String message, HttpStatus status) {
242 ResponseEntity<T> re = new ResponseEntity<>((T) message, status);
243 return Mono.just(re);
246 private <T> Mono<ResponseEntity<T>> handleException(Throwable throwable) {
247 if (throwable instanceof WebClientResponseException) {
248 WebClientResponseException e = (WebClientResponseException) throwable;
249 return createResponseEntity(e.getResponseBodyAsString(), e.getStatusCode());
250 } else if (throwable instanceof RejectionException) {
251 RejectionException e = (RejectionException) throwable;
252 return createResponseEntity(e.getMessage(), e.getStatus());
254 return createResponseEntity(throwable.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
258 private Mono<Object> validateModifiedPolicy(Policy policy) {
259 // Check that ric is not updated
260 Policy current = this.policies.get(policy.id());
261 if (current != null && !current.ric().name().equals(policy.ric().name())) {
262 RejectionException e = new RejectionException("Policy cannot change RIC, policyId: " + current.id() + //
263 ", RIC name: " + current.ric().name() + //
264 ", new name: " + policy.ric().name(), HttpStatus.CONFLICT);
265 return Mono.error(e);
267 return Mono.just("OK");
270 private Mono<Object> assertRicStateIdle(Ric ric) {
271 if (ric.getState() == Ric.RicState.AVAILABLE) {
272 return Mono.just("OK");
274 RejectionException e = new RejectionException(
275 "Ric is not operational, RIC name: " + ric.name() + ", state: " + ric.getState(), HttpStatus.LOCKED);
276 return Mono.error(e);
280 @GetMapping("/policies")
281 @ApiOperation(value = "Query policies")
284 @ApiResponse(code = 200, message = "Policies", response = PolicyInfo.class, responseContainer = "List"),
285 @ApiResponse(code = 404, message = "RIC or type not found", response = String.class)})
286 public ResponseEntity<String> getPolicies( //
287 @RequestParam(name = "type", required = false) String type, //
288 @RequestParam(name = "ric", required = false) String ric, //
289 @RequestParam(name = "service", required = false) String service) //
291 if ((type != null && this.policyTypes.get(type) == null)) {
292 return new ResponseEntity<>("Policy type not found", HttpStatus.NOT_FOUND);
294 if ((ric != null && this.rics.get(ric) == null)) {
295 return new ResponseEntity<>("RIC not found", HttpStatus.NOT_FOUND);
298 String filteredPolicies = policiesToJson(filter(type, ric, service));
299 return new ResponseEntity<>(filteredPolicies, HttpStatus.OK);
302 @GetMapping("/policy_ids")
303 @ApiOperation(value = "Query policies, only IDs returned")
305 value = {@ApiResponse(code = 200, message = "Policy ids", response = String.class, responseContainer = "List"),
306 @ApiResponse(code = 404, message = "RIC or type not found", response = String.class)})
307 public ResponseEntity<String> getPolicyIds( //
308 @RequestParam(name = "type", required = false) String type, //
309 @RequestParam(name = "ric", required = false) String ric, //
310 @RequestParam(name = "service", required = false) String service) //
312 if ((type != null && this.policyTypes.get(type) == null)) {
313 return new ResponseEntity<>("Policy type not found", HttpStatus.NOT_FOUND);
315 if ((ric != null && this.rics.get(ric) == null)) {
316 return new ResponseEntity<>("RIC not found", HttpStatus.NOT_FOUND);
319 String policyIdsJson = toPolicyIdsJson(filter(type, ric, service));
320 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 = "id", required = true) String id) {
333 Policy policy = policies.getPolicy(id);
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) {
371 return filter(policies.getForType(type), null, ric, service);
372 } else if (service != null) {
373 return filter(policies.getForService(service), type, ric, null);
374 } else if (ric != null) {
375 return filter(policies.getForRic(ric), type, null, service);
377 return policies.getAll();
381 private String policiesToJson(Collection<Policy> policies) {
382 List<PolicyInfo> v = new ArrayList<>(policies.size());
383 for (Policy p : policies) {
384 PolicyInfo policyInfo = new PolicyInfo();
385 policyInfo.id = p.id();
386 policyInfo.json = fromJson(p.json());
387 policyInfo.ric = p.ric().name();
388 policyInfo.type = p.type().name();
389 policyInfo.service = p.ownerServiceName();
390 policyInfo.lastModified = p.lastModified();
391 if (!policyInfo.validate()) {
392 throw new NullPointerException("BUG, all fields must be set");
396 return gson.toJson(v);
399 private Object fromJson(String jsonStr) {
400 return gson.fromJson(jsonStr, Object.class);
403 private String toPolicyTypeSchemasJson(Collection<PolicyType> types) {
404 StringBuilder result = new StringBuilder();
406 boolean first = true;
407 for (PolicyType t : types) {
412 result.append(t.schema());
415 return result.toString();
418 private String toPolicyTypeIdsJson(Collection<PolicyType> types) {
419 List<String> v = new ArrayList<>(types.size());
420 for (PolicyType t : types) {
423 return gson.toJson(v);
426 private String toPolicyIdsJson(Collection<Policy> policies) {
427 List<String> v = new ArrayList<>(policies.size());
428 for (Policy p : policies) {
431 return gson.toJson(v);
434 private String getTimeStampUtc() {
435 return java.time.Instant.now().toString();