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 @RequestParam(name = "transient", required = false, defaultValue = "false") boolean isTransient, //
213 @RequestBody Object jsonBody) {
215 String jsonString = gson.toJson(jsonBody);
216 Ric ric = rics.get(ricName);
217 PolicyType type = policyTypes.get(typeName);
218 keepServiceAlive(service);
219 if (ric == null || type == null) {
220 return Mono.just(new ResponseEntity<>(HttpStatus.NOT_FOUND));
222 Policy policy = ImmutablePolicy.builder() //
227 .ownerServiceName(service) //
228 .lastModified(getTimeStampUtc()) //
229 .isTransient(isTransient) //
232 final boolean isCreate = this.policies.get(policy.id()) == null;
234 return ric.getLock().lock(LockType.SHARED) //
235 .flatMap(notUsed -> assertRicStateIdle(ric)) //
236 .flatMap(notUsed -> checkSupportedType(ric, type)) //
237 .flatMap(notUsed -> validateModifiedPolicy(policy)) //
238 .flatMap(notUsed -> a1ClientFactory.createA1Client(ric)) //
239 .flatMap(client -> client.putPolicy(policy)) //
240 .doOnNext(notUsed -> policies.put(policy)) //
241 .doOnNext(notUsed -> ric.getLock().unlockBlocking()) //
242 .doOnError(trowable -> ric.getLock().unlockBlocking()) //
243 .flatMap(notUsed -> Mono.just(new ResponseEntity<>(isCreate ? HttpStatus.CREATED : HttpStatus.OK))) //
244 .onErrorResume(this::handleException);
247 @SuppressWarnings({"unchecked"})
248 private <T> Mono<ResponseEntity<T>> createResponseEntity(String message, HttpStatus status) {
249 ResponseEntity<T> re = new ResponseEntity<>((T) message, status);
250 return Mono.just(re);
253 private <T> Mono<ResponseEntity<T>> handleException(Throwable throwable) {
254 if (throwable instanceof WebClientResponseException) {
255 WebClientResponseException e = (WebClientResponseException) throwable;
256 return createResponseEntity(e.getResponseBodyAsString(), e.getStatusCode());
257 } else if (throwable instanceof RejectionException) {
258 RejectionException e = (RejectionException) throwable;
259 return createResponseEntity(e.getMessage(), e.getStatus());
261 return createResponseEntity(throwable.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
265 private Mono<Object> validateModifiedPolicy(Policy policy) {
266 // Check that ric is not updated
267 Policy current = this.policies.get(policy.id());
268 if (current != null && !current.ric().name().equals(policy.ric().name())) {
269 RejectionException e = new RejectionException("Policy cannot change RIC, policyId: " + current.id() + //
270 ", RIC name: " + current.ric().name() + //
271 ", new name: " + policy.ric().name(), HttpStatus.CONFLICT);
272 logger.debug("Request rejected, {}", e);
273 return Mono.error(e);
275 return Mono.just("OK");
278 private Mono<Object> checkSupportedType(Ric ric, PolicyType type) {
279 if (!ric.isSupportingType(type.name())) {
280 logger.debug("Request rejected, type not supported, RIC: {}", ric);
281 RejectionException e = new RejectionException(
282 "Type: " + type.name() + " not supported by RIC: " + ric.name(), HttpStatus.NOT_FOUND);
283 return Mono.error(e);
285 return Mono.just("OK");
288 private Mono<Object> assertRicStateIdle(Ric ric) {
289 if (ric.getState() == Ric.RicState.AVAILABLE) {
290 return Mono.just("OK");
292 logger.debug("Request rejected RIC not IDLE, ric: {}", ric);
293 RejectionException e = new RejectionException(
294 "Ric is not operational, RIC name: " + ric.name() + ", state: " + ric.getState(), HttpStatus.LOCKED);
295 return Mono.error(e);
299 @GetMapping("/policies")
300 @ApiOperation(value = "Query policies")
303 @ApiResponse(code = 200, message = "Policies", response = PolicyInfo.class, responseContainer = "List"),
304 @ApiResponse(code = 404, message = "RIC or type not found", response = String.class)})
305 public ResponseEntity<String> getPolicies( //
306 @RequestParam(name = "type", required = false) String type, //
307 @RequestParam(name = "ric", required = false) String ric, //
308 @RequestParam(name = "service", required = false) String service) //
310 if ((type != null && this.policyTypes.get(type) == null)) {
311 return new ResponseEntity<>("Policy type not found", HttpStatus.NOT_FOUND);
313 if ((ric != null && this.rics.get(ric) == null)) {
314 return new ResponseEntity<>("RIC not found", HttpStatus.NOT_FOUND);
317 String filteredPolicies = policiesToJson(filter(type, ric, service));
318 return new ResponseEntity<>(filteredPolicies, HttpStatus.OK);
321 @GetMapping("/policy_ids")
322 @ApiOperation(value = "Query policies, only IDs returned")
324 value = {@ApiResponse(code = 200, message = "Policy ids", response = String.class, responseContainer = "List"),
325 @ApiResponse(code = 404, message = "RIC or type not found", response = String.class)})
326 public ResponseEntity<String> getPolicyIds( //
327 @RequestParam(name = "type", required = false) String type, //
328 @RequestParam(name = "ric", required = false) String ric, //
329 @RequestParam(name = "service", required = false) String service) //
331 if ((type != null && this.policyTypes.get(type) == null)) {
332 return new ResponseEntity<>("Policy type not found", HttpStatus.NOT_FOUND);
334 if ((ric != null && this.rics.get(ric) == null)) {
335 return new ResponseEntity<>("RIC not found", HttpStatus.NOT_FOUND);
338 String policyIdsJson = toPolicyIdsJson(filter(type, ric, service));
339 return new ResponseEntity<>(policyIdsJson, HttpStatus.OK);
342 @GetMapping("/policy_status")
343 @ApiOperation(value = "Returns a policy status") //
346 @ApiResponse(code = 200, message = "Policy status", response = Object.class), //
347 @ApiResponse(code = 404, message = "Policy is not found", response = String.class)} //
349 public Mono<ResponseEntity<String>> getPolicyStatus( //
350 @RequestParam(name = "id", required = true) String id) {
352 Policy policy = policies.getPolicy(id);
354 return a1ClientFactory.createA1Client(policy.ric()) //
355 .flatMap(client -> client.getPolicyStatus(policy)) //
356 .flatMap(status -> Mono.just(new ResponseEntity<>(status, HttpStatus.OK)))
357 .onErrorResume(this::handleException);
358 } catch (ServiceException e) {
359 return Mono.just(new ResponseEntity<>(e.getMessage(), HttpStatus.NOT_FOUND));
363 private void keepServiceAlive(String name) {
364 Service s = this.services.get(name);
370 private boolean include(String filter, String value) {
371 return filter == null || value.equals(filter);
374 private Collection<Policy> filter(Collection<Policy> collection, String type, String ric, String service) {
375 if (type == null && ric == null && service == null) {
378 List<Policy> filtered = new ArrayList<>();
379 for (Policy p : collection) {
380 if (include(type, p.type().name()) && include(ric, p.ric().name())
381 && include(service, p.ownerServiceName())) {
388 private Collection<Policy> filter(String type, String ric, String service) {
390 return filter(policies.getForType(type), null, ric, service);
391 } else if (service != null) {
392 return filter(policies.getForService(service), type, ric, null);
393 } else if (ric != null) {
394 return filter(policies.getForRic(ric), type, null, service);
396 return policies.getAll();
400 private String policiesToJson(Collection<Policy> policies) {
401 List<PolicyInfo> v = new ArrayList<>(policies.size());
402 for (Policy p : policies) {
403 PolicyInfo policyInfo = new PolicyInfo();
404 policyInfo.id = p.id();
405 policyInfo.json = fromJson(p.json());
406 policyInfo.ric = p.ric().name();
407 policyInfo.type = p.type().name();
408 policyInfo.service = p.ownerServiceName();
409 policyInfo.lastModified = p.lastModified();
410 if (!policyInfo.validate()) {
411 logger.error("BUG, all fields must be set");
415 return gson.toJson(v);
418 private Object fromJson(String jsonStr) {
419 return gson.fromJson(jsonStr, Object.class);
422 private String toPolicyTypeSchemasJson(Collection<PolicyType> types) {
423 StringBuilder result = new StringBuilder();
425 boolean first = true;
426 for (PolicyType t : types) {
431 result.append(t.schema());
434 return result.toString();
437 private String toPolicyTypeIdsJson(Collection<PolicyType> types) {
438 List<String> v = new ArrayList<>(types.size());
439 for (PolicyType t : types) {
442 return gson.toJson(v);
445 private String toPolicyIdsJson(Collection<Policy> policies) {
446 List<String> v = new ArrayList<>(policies.size());
447 for (Policy p : policies) {
450 return gson.toJson(v);
453 private String getTimeStampUtc() {
454 return java.time.Instant.now().toString();