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.Lock.LockType;
40 import org.oransc.policyagent.repository.Policies;
41 import org.oransc.policyagent.repository.Policy;
42 import org.oransc.policyagent.repository.PolicyType;
43 import org.oransc.policyagent.repository.PolicyTypes;
44 import org.oransc.policyagent.repository.Ric;
45 import org.oransc.policyagent.repository.Rics;
46 import org.springframework.beans.factory.annotation.Autowired;
47 import org.springframework.http.HttpStatus;
48 import org.springframework.http.ResponseEntity;
49 import org.springframework.web.bind.annotation.DeleteMapping;
50 import org.springframework.web.bind.annotation.GetMapping;
51 import org.springframework.web.bind.annotation.PutMapping;
52 import org.springframework.web.bind.annotation.RequestBody;
53 import org.springframework.web.bind.annotation.RequestParam;
54 import org.springframework.web.bind.annotation.RestController;
55 import reactor.core.publisher.Mono;
58 @Api(tags = "A1 Policy Management")
59 public class PolicyController {
61 private final Rics rics;
62 private final PolicyTypes policyTypes;
63 private final Policies policies;
64 private final A1ClientFactory a1ClientFactory;
66 private static Gson gson = new GsonBuilder() //
71 PolicyController(ApplicationConfig config, PolicyTypes types, Policies policies, Rics rics,
72 A1ClientFactory a1ClientFactory) {
73 this.policyTypes = types;
74 this.policies = policies;
76 this.a1ClientFactory = a1ClientFactory;
79 @GetMapping("/policy_schemas")
80 @ApiOperation(value = "Returns policy type schema definitions")
83 @ApiResponse(code = 200, message = "Policy schemas", response = Object.class, responseContainer = "List"), //
84 @ApiResponse(code = 404, message = "RIC is not found", response = String.class)})
85 public ResponseEntity<String> getPolicySchemas(@RequestParam(name = "ric", required = false) String ricName) {
86 synchronized (this.policyTypes) {
87 if (ricName == null) {
88 Collection<PolicyType> types = this.policyTypes.getAll();
89 return new ResponseEntity<>(toPolicyTypeSchemasJson(types), HttpStatus.OK);
92 Collection<PolicyType> types = rics.getRic(ricName).getSupportedPolicyTypes();
93 return new ResponseEntity<>(toPolicyTypeSchemasJson(types), HttpStatus.OK);
94 } catch (ServiceException e) {
95 return new ResponseEntity<>(e.toString(), HttpStatus.NOT_FOUND);
101 @GetMapping("/policy_schema")
102 @ApiOperation(value = "Returns one policy type schema definition")
105 @ApiResponse(code = 200, message = "Policy schema", response = Object.class),
106 @ApiResponse(code = 404, message = "RIC is not found", response = String.class)})
107 public ResponseEntity<String> getPolicySchema(@RequestParam(name = "id", required = true) String id) {
109 PolicyType type = policyTypes.getType(id);
110 return new ResponseEntity<>(type.schema(), HttpStatus.OK);
111 } catch (ServiceException e) {
112 return new ResponseEntity<>(e.toString(), HttpStatus.NOT_FOUND);
116 @GetMapping("/policy_types")
117 @ApiOperation(value = "Query policy type names")
122 message = "Policy type names",
123 response = String.class,
124 responseContainer = "List"),
125 @ApiResponse(code = 404, message = "RIC is not found", response = String.class)})
126 public ResponseEntity<String> getPolicyTypes(@RequestParam(name = "ric", required = false) String ricName) {
127 synchronized (this.policyTypes) {
128 if (ricName == null) {
129 Collection<PolicyType> types = this.policyTypes.getAll();
130 return new ResponseEntity<>(toPolicyTypeIdsJson(types), HttpStatus.OK);
133 Collection<PolicyType> types = rics.getRic(ricName).getSupportedPolicyTypes();
134 return new ResponseEntity<>(toPolicyTypeIdsJson(types), HttpStatus.OK);
135 } catch (ServiceException e) {
136 return new ResponseEntity<>(e.toString(), HttpStatus.NOT_FOUND);
142 @GetMapping("/policy")
143 @ApiOperation(value = "Returns a policy configuration") //
146 @ApiResponse(code = 200, message = "Policy found", response = Object.class), //
147 @ApiResponse(code = 404, message = "Policy is not found")} //
149 public ResponseEntity<String> getPolicy( //
150 @RequestParam(name = "instance", required = true) String instance) {
152 Policy p = policies.getPolicy(instance);
153 return new ResponseEntity<>(p.json(), HttpStatus.OK);
154 } catch (ServiceException e) {
155 return new ResponseEntity<>(e.getMessage(), HttpStatus.NOT_FOUND);
159 @DeleteMapping("/policy")
160 @ApiOperation(value = "Delete a policy", response = Object.class)
163 @ApiResponse(code = 204, message = "Policy deleted", response = Object.class),
164 @ApiResponse(code = 404, message = "Policy is not found", response = String.class),
165 @ApiResponse(code = 423, message = "RIC is locked", response = String.class)})
166 public Mono<ResponseEntity<Object>> deletePolicy( //
167 @RequestParam(name = "instance", required = true) String id) {
168 Policy policy = policies.get(id);
169 if (policy != null && policy.ric().getState() == Ric.RicState.IDLE) {
170 Ric ric = policy.ric();
171 return ric.getLock().lock(LockType.SHARED) // //
172 .flatMap(lock -> a1ClientFactory.createA1Client(policy.ric())) //
173 .doOnNext(notUsed -> policies.remove(policy)) //
174 .flatMap(client -> client.deletePolicy(policy)) //
175 .doOnNext(notUsed -> ric.getLock().unlockBlocking()) //
176 .doOnError(notUsed -> ric.getLock().unlockBlocking()) //
177 .flatMap(notUsed -> Mono.just(new ResponseEntity<>(HttpStatus.NO_CONTENT)));
178 } else if (policy != null) {
179 return Mono.just(new ResponseEntity<>("Busy, recovering", HttpStatus.LOCKED));
181 return Mono.just(new ResponseEntity<>(HttpStatus.NOT_FOUND));
185 @PutMapping(path = "/policy")
186 @ApiOperation(value = "Put a policy", response = String.class)
189 @ApiResponse(code = 201, message = "Policy created"), //
190 @ApiResponse(code = 200, message = "Policy updated"), //
191 @ApiResponse(code = 423, message = "RIC is locked", response = String.class), //
192 @ApiResponse(code = 404, message = "RIC or policy type is not found", response = String.class), //
193 @ApiResponse(code = 405, message = "Change is not allowed", response = String.class)})
194 public Mono<ResponseEntity<Object>> putPolicy( //
195 @RequestParam(name = "type", required = true) String typeName, //
196 @RequestParam(name = "instance", required = true) String instanceId, //
197 @RequestParam(name = "ric", required = true) String ricName, //
198 @RequestParam(name = "service", required = true) String service, //
199 @RequestBody Object jsonBody) {
201 String jsonString = gson.toJson(jsonBody);
202 Ric ric = rics.get(ricName);
203 PolicyType type = policyTypes.get(typeName);
204 if (ric != null && type != null && ric.getState() == Ric.RicState.IDLE) {
205 Policy policy = ImmutablePolicy.builder() //
210 .ownerServiceName(service) //
211 .lastModified(getTimeStampUtc()) //
214 final boolean isCreate = this.policies.get(policy.id()) == null;
216 return ric.getLock().lock(LockType.SHARED) //
217 .flatMap(p -> validateModifiedPolicy(policy)) //
218 .flatMap(notUsed -> a1ClientFactory.createA1Client(ric)) //
219 .flatMap(client -> client.putPolicy(policy)) //
220 .doOnNext(notUsed -> policies.put(policy)) //
221 .doOnNext(notUsed -> ric.getLock().unlockBlocking()) //
222 .doOnError(t -> ric.getLock().unlockBlocking()) //
223 .flatMap(notUsed -> Mono.just(new ResponseEntity<>(isCreate ? HttpStatus.CREATED : HttpStatus.OK))) //
224 .onErrorResume(t -> Mono.just(new ResponseEntity<>(t.getMessage(), HttpStatus.METHOD_NOT_ALLOWED)));
227 return ric == null || type == null ? Mono.just(new ResponseEntity<>(HttpStatus.NOT_FOUND))
228 : Mono.just(new ResponseEntity<>(HttpStatus.LOCKED)); // Recovering
231 private Mono<Object> validateModifiedPolicy(Policy policy) {
232 // Check that ric is not updated
233 Policy current = this.policies.get(policy.id());
234 if (current != null && !current.ric().name().equals(policy.ric().name())) {
235 return Mono.error(new Exception("Policy cannot change RIC, policyId: " + current.id() + //
236 ", RIC name: " + current.ric().name() + //
237 ", new name: " + policy.ric().name()));
239 return Mono.just("OK");
242 @GetMapping("/policies")
243 @ApiOperation(value = "Query policies")
246 @ApiResponse(code = 200, message = "Policies", response = PolicyInfo.class, responseContainer = "List"),
247 @ApiResponse(code = 404, message = "RIC or type not found", response = String.class)})
248 public ResponseEntity<String> getPolicies( //
249 @RequestParam(name = "type", required = false) String type, //
250 @RequestParam(name = "ric", required = false) String ric, //
251 @RequestParam(name = "service", required = false) String service) //
253 if ((type != null && this.policyTypes.get(type) == null)) {
254 return new ResponseEntity<>("Policy type not found", HttpStatus.NOT_FOUND);
256 if ((ric != null && this.rics.get(ric) == null)) {
257 return new ResponseEntity<>("RIC not found", HttpStatus.NOT_FOUND);
259 synchronized (policies) {
260 Collection<Policy> result = null;
263 result = policies.getForType(type);
264 result = filter(result, null, ric, service);
265 } else if (service != null) {
266 result = policies.getForService(service);
267 result = filter(result, type, ric, null);
268 } else if (ric != null) {
269 result = filter(policies.getForRic(ric), type, null, service);
271 result = policies.getAll();
276 policiesJson = policiesToJson(result);
277 } catch (ServiceException e) {
278 return new ResponseEntity<>(e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
280 return new ResponseEntity<>(policiesJson, HttpStatus.OK);
284 @GetMapping("/policy_status")
285 @ApiOperation(value = "Returns a policy status") //
288 @ApiResponse(code = 200, message = "Policy status", response = Object.class), //
289 @ApiResponse(code = 404, message = "Policy is not found", response = String.class)} //
291 public Mono<ResponseEntity<String>> getPolicyStatus( //
292 @RequestParam(name = "instance", required = true) String instance) {
294 Policy policy = policies.getPolicy(instance);
296 return a1ClientFactory.createA1Client(policy.ric()) //
297 .flatMap(client -> client.getPolicyStatus(policy)) //
298 .flatMap(status -> Mono.just(new ResponseEntity<>(status, HttpStatus.OK)));
299 } catch (ServiceException e) {
300 return Mono.just(new ResponseEntity<>(e.getMessage(), HttpStatus.NOT_FOUND));
304 private boolean include(String filter, String value) {
305 return filter == null || value.equals(filter);
308 private Collection<Policy> filter(Collection<Policy> collection, String type, String ric, String service) {
309 if (type == null && ric == null && service == null) {
312 List<Policy> filtered = new ArrayList<>();
313 for (Policy p : collection) {
314 if (include(type, p.type().name()) && include(ric, p.ric().name())
315 && include(service, p.ownerServiceName())) {
322 private String policiesToJson(Collection<Policy> policies) throws ServiceException {
323 List<PolicyInfo> v = new ArrayList<>(policies.size());
324 for (Policy p : policies) {
325 PolicyInfo policyInfo = new PolicyInfo();
326 policyInfo.id = p.id();
327 policyInfo.json = fromJson(p.json());
328 policyInfo.ric = p.ric().name();
329 policyInfo.type = p.type().name();
330 policyInfo.service = p.ownerServiceName();
331 policyInfo.lastModified = p.lastModified();
332 if (!policyInfo.validate()) {
333 throw new ServiceException("BUG, all fields must be set");
337 return gson.toJson(v);
340 private Object fromJson(String jsonStr) {
341 return gson.fromJson(jsonStr, Object.class);
344 private String toPolicyTypeSchemasJson(Collection<PolicyType> types) {
345 StringBuilder result = new StringBuilder();
347 boolean first = true;
348 for (PolicyType t : types) {
353 result.append(t.schema());
356 return result.toString();
359 private String toPolicyTypeIdsJson(Collection<PolicyType> types) {
360 List<String> v = new ArrayList<>(types.size());
361 for (PolicyType t : types) {
364 return gson.toJson(v);
367 private String getTimeStampUtc() {
368 return java.time.Instant.now().toString();