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;
35 import org.oransc.policyagent.clients.A1ClientFactory;
36 import org.oransc.policyagent.configuration.ApplicationConfig;
37 import org.oransc.policyagent.exceptions.ServiceException;
38 import org.oransc.policyagent.repository.ImmutablePolicy;
39 import org.oransc.policyagent.repository.Policies;
40 import org.oransc.policyagent.repository.Policy;
41 import org.oransc.policyagent.repository.PolicyType;
42 import org.oransc.policyagent.repository.PolicyTypes;
43 import org.oransc.policyagent.repository.Ric;
44 import org.oransc.policyagent.repository.Rics;
45 import org.springframework.beans.factory.annotation.Autowired;
46 import org.springframework.http.HttpStatus;
47 import org.springframework.http.ResponseEntity;
48 import org.springframework.web.bind.annotation.DeleteMapping;
49 import org.springframework.web.bind.annotation.GetMapping;
50 import org.springframework.web.bind.annotation.PutMapping;
51 import org.springframework.web.bind.annotation.RequestBody;
52 import org.springframework.web.bind.annotation.RequestParam;
53 import org.springframework.web.bind.annotation.RestController;
54 import reactor.core.publisher.Mono;
57 @Api(value = "Policy Management API")
58 public class PolicyController {
60 private final Rics rics;
61 private final PolicyTypes policyTypes;
62 private final Policies policies;
63 private final A1ClientFactory a1ClientFactory;
65 private static Gson gson = new GsonBuilder() //
70 PolicyController(ApplicationConfig config, PolicyTypes types, Policies policies, Rics rics,
71 A1ClientFactory a1ClientFactory) {
72 this.policyTypes = types;
73 this.policies = policies;
75 this.a1ClientFactory = a1ClientFactory;
78 @GetMapping("/policy_schemas")
79 @ApiOperation(value = "Returns policy type schema definitions")
82 @ApiResponse(code = 200, message = "Policy schemas", response = Object.class, responseContainer = "List")})
83 public ResponseEntity<String> getPolicySchemas(@RequestParam(name = "ric", required = false) String ricName) {
84 synchronized (this.policyTypes) {
85 if (ricName == null) {
86 Collection<PolicyType> types = this.policyTypes.getAll();
87 return new ResponseEntity<>(toPolicyTypeSchemasJson(types), HttpStatus.OK);
90 Collection<PolicyType> types = rics.getRic(ricName).getSupportedPolicyTypes();
91 return new ResponseEntity<>(toPolicyTypeSchemasJson(types), HttpStatus.OK);
92 } catch (ServiceException e) {
93 return new ResponseEntity<>(e.toString(), HttpStatus.NOT_FOUND);
99 @GetMapping("/policy_schema")
100 @ApiOperation(value = "Returns one policy type schema definition")
101 @ApiResponses(value = {@ApiResponse(code = 200, message = "Policy schema", response = Object.class)})
102 public ResponseEntity<String> getPolicySchema(@RequestParam(name = "id", required = true) String id) {
104 PolicyType type = policyTypes.getType(id);
105 return new ResponseEntity<>(type.schema(), HttpStatus.OK);
106 } catch (ServiceException e) {
107 return new ResponseEntity<>(e.toString(), HttpStatus.NOT_FOUND);
111 @GetMapping("/policy_types")
112 @ApiOperation(value = "Query policy type names")
114 value = {@ApiResponse(
116 message = "Policy type names",
117 response = String.class,
118 responseContainer = "List")})
119 public ResponseEntity<String> getPolicyTypes(@RequestParam(name = "ric", required = false) String ricName) {
120 synchronized (this.policyTypes) {
121 if (ricName == null) {
122 Collection<PolicyType> types = this.policyTypes.getAll();
123 return new ResponseEntity<>(toPolicyTypeIdsJson(types), HttpStatus.OK);
126 Collection<PolicyType> types = rics.getRic(ricName).getSupportedPolicyTypes();
127 return new ResponseEntity<>(toPolicyTypeIdsJson(types), HttpStatus.OK);
128 } catch (ServiceException e) {
129 return new ResponseEntity<>(e.toString(), HttpStatus.NOT_FOUND);
135 @GetMapping("/policy")
136 @ApiOperation(value = "Returns a policy configuration") //
139 @ApiResponse(code = 200, message = "Policy found", response = Object.class), //
140 @ApiResponse(code = 204, message = "Policy is not found")} //
142 public ResponseEntity<String> getPolicy( //
143 @RequestParam(name = "instance", required = true) String instance) {
145 Policy p = policies.getPolicy(instance);
146 return new ResponseEntity<>(p.json(), HttpStatus.OK);
147 } catch (ServiceException e) {
148 return new ResponseEntity<>(e.getMessage(), HttpStatus.NO_CONTENT);
152 @DeleteMapping("/policy")
153 @ApiOperation(value = "Delete a policy", response = Object.class)
154 @ApiResponses(value = {@ApiResponse(code = 204, message = "Policy deleted", response = Object.class)})
155 public Mono<ResponseEntity<Void>> deletePolicy( //
156 @RequestParam(name = "instance", required = true) String id) {
157 Policy policy = policies.get(id);
158 if (policy != null && policy.ric().getState() == Ric.RicState.IDLE) {
159 policies.remove(policy);
160 return a1ClientFactory.createA1Client(policy.ric()) //
161 .flatMap(client -> client.deletePolicy(policy)) //
162 .flatMap(notUsed -> Mono.just(new ResponseEntity<>(HttpStatus.NO_CONTENT)));
164 return Mono.just(new ResponseEntity<>(HttpStatus.NOT_FOUND));
168 @PutMapping(path = "/policy")
169 @ApiOperation(value = "Put a policy", response = String.class)
170 @ApiResponses(value = {@ApiResponse(code = 200, message = "Policy created or updated")})
171 public Mono<ResponseEntity<String>> putPolicy( //
172 @RequestParam(name = "type", required = true) String typeName, //
173 @RequestParam(name = "instance", required = true) String instanceId, //
174 @RequestParam(name = "ric", required = true) String ricName, //
175 @RequestParam(name = "service", required = true) String service, //
176 @RequestBody Object jsonBody) {
178 String jsonString = gson.toJson(jsonBody);
180 Ric ric = rics.get(ricName);
181 PolicyType type = policyTypes.get(typeName);
182 if (ric != null && type != null && ric.getState() == Ric.RicState.IDLE) {
183 Policy policy = ImmutablePolicy.builder() //
188 .ownerServiceName(service) //
189 .lastModified(getTimeStampUtc()) //
192 return validateModifiedPolicy(policy) //
193 .flatMap(x -> a1ClientFactory.createA1Client(ric)) //
194 .flatMap(client -> client.putPolicy(policy)) //
195 .doOnNext(notUsed -> policies.put(policy)) //
196 .flatMap(notUsed -> Mono.just(new ResponseEntity<>(HttpStatus.OK)));
198 return Mono.just(new ResponseEntity<>(HttpStatus.NOT_FOUND));
201 private Mono<Object> validateModifiedPolicy(Policy policy) {
202 // Check that ric is not updated
203 Policy current = this.policies.get(policy.id());
204 if (current != null) {
205 if (!current.ric().name().equals(policy.ric().name())) {
206 return Mono.error(new Exception("Policy cannot change RIC or service"));
209 return Mono.just("OK");
212 @GetMapping("/policies")
213 @ApiOperation(value = "Query policies")
216 @ApiResponse(code = 200, message = "Policies", response = PolicyInfo.class, responseContainer = "List")})
217 public ResponseEntity<String> getPolicies( //
218 @RequestParam(name = "type", required = false) String type, //
219 @RequestParam(name = "ric", required = false) String ric, //
220 @RequestParam(name = "service", required = false) String service) //
222 synchronized (policies) {
223 Collection<Policy> result = null;
226 result = policies.getForType(type);
227 result = filter(result, null, ric, service);
228 } else if (service != null) {
229 result = policies.getForService(service);
230 result = filter(result, type, ric, null);
231 } else if (ric != null) {
232 result = filter(policies.getForRic(ric), type, null, service);
234 result = policies.getAll();
239 policiesJson = policiesToJson(result);
240 } catch (ServiceException e) {
241 return new ResponseEntity<>(e.getMessage(), HttpStatus.NO_CONTENT);
243 return new ResponseEntity<>(policiesJson, HttpStatus.OK);
247 @GetMapping("/policy_status")
248 @ApiOperation(value = "Returns a policy status") //
251 @ApiResponse(code = 200, message = "Policy status", response = Object.class), //
252 @ApiResponse(code = 204, message = "Policy is not found", response = String.class)} //
254 public Mono<ResponseEntity<String>> getPolicyStatus( //
255 @RequestParam(name = "instance", required = true) String instance) {
257 Policy policy = policies.getPolicy(instance);
259 return a1ClientFactory.createA1Client(policy.ric()) //
260 .flatMap(client -> client.getPolicyStatus(policy)) //
261 .flatMap(status -> Mono.just(new ResponseEntity<>(status, HttpStatus.OK)));
262 } catch (ServiceException e) {
263 return Mono.just(new ResponseEntity<>(e.getMessage(), HttpStatus.NO_CONTENT));
267 private boolean include(String filter, String value) {
268 return filter == null || value.equals(filter);
271 private Collection<Policy> filter(Collection<Policy> collection, String type, String ric, String service) {
272 if (type == null && ric == null && service == null) {
275 List<Policy> filtered = new ArrayList<>();
276 for (Policy p : collection) {
277 if (include(type, p.type().name()) && include(ric, p.ric().name())
278 && include(service, p.ownerServiceName())) {
285 private String policiesToJson(Collection<Policy> policies) throws ServiceException {
286 List<PolicyInfo> v = new ArrayList<>(policies.size());
287 for (Policy p : policies) {
288 PolicyInfo policyInfo = new PolicyInfo();
289 policyInfo.id = p.id();
290 policyInfo.json = fromJson(p.json());
291 policyInfo.ric = p.ric().name();
292 policyInfo.type = p.type().name();
293 policyInfo.service = p.ownerServiceName();
294 policyInfo.lastModified = p.lastModified();
295 if (!policyInfo.validate()) {
296 throw new ServiceException("BUG, all fields must be set");
300 return gson.toJson(v);
303 private Object fromJson(String jsonStr) {
304 return gson.fromJson(jsonStr, Object.class);
307 private String toPolicyTypeSchemasJson(Collection<PolicyType> types) {
308 StringBuilder result = new StringBuilder();
310 boolean first = true;
311 for (PolicyType t : types) {
316 result.append(t.schema());
319 return result.toString();
322 private String toPolicyTypeIdsJson(Collection<PolicyType> types) {
323 List<String> v = new ArrayList<>(types.size());
324 for (PolicyType t : types) {
327 return gson.toJson(v);
330 private String getTimeStampUtc() {
331 return java.time.Instant.now().toString();