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.exceptions.ServiceException;
37 import org.oransc.policyagent.repository.ImmutablePolicy;
38 import org.oransc.policyagent.repository.Lock.LockType;
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.oransc.policyagent.repository.Service;
46 import org.oransc.policyagent.repository.Services;
47 import org.springframework.beans.factory.annotation.Autowired;
48 import org.springframework.http.HttpStatus;
49 import org.springframework.http.ResponseEntity;
50 import org.springframework.web.bind.annotation.DeleteMapping;
51 import org.springframework.web.bind.annotation.GetMapping;
52 import org.springframework.web.bind.annotation.PutMapping;
53 import org.springframework.web.bind.annotation.RequestBody;
54 import org.springframework.web.bind.annotation.RequestParam;
55 import org.springframework.web.bind.annotation.RestController;
56 import reactor.core.publisher.Mono;
59 @Api(tags = "A1 Policy Management")
60 public class PolicyController {
65 private PolicyTypes policyTypes;
67 private Policies policies;
69 private A1ClientFactory a1ClientFactory;
71 private Services services;
73 private static Gson gson = new GsonBuilder() //
77 @GetMapping("/policy_schemas")
78 @ApiOperation(value = "Returns policy type schema definitions")
81 @ApiResponse(code = 200, message = "Policy schemas", response = Object.class, responseContainer = "List"), //
82 @ApiResponse(code = 404, message = "RIC is not found", response = String.class)})
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")
103 @ApiResponse(code = 200, message = "Policy schema", response = Object.class),
104 @ApiResponse(code = 404, message = "RIC is not found", response = String.class)})
105 public ResponseEntity<String> getPolicySchema(@RequestParam(name = "id", required = true) String id) {
107 PolicyType type = policyTypes.getType(id);
108 return new ResponseEntity<>(type.schema(), HttpStatus.OK);
109 } catch (ServiceException e) {
110 return new ResponseEntity<>(e.toString(), HttpStatus.NOT_FOUND);
114 @GetMapping("/policy_types")
115 @ApiOperation(value = "Query policy type names")
120 message = "Policy type names",
121 response = String.class,
122 responseContainer = "List"),
123 @ApiResponse(code = 404, message = "RIC is not found", response = String.class)})
124 public ResponseEntity<String> getPolicyTypes(@RequestParam(name = "ric", required = false) String ricName) {
125 synchronized (this.policyTypes) {
126 if (ricName == null) {
127 Collection<PolicyType> types = this.policyTypes.getAll();
128 return new ResponseEntity<>(toPolicyTypeIdsJson(types), HttpStatus.OK);
131 Collection<PolicyType> types = rics.getRic(ricName).getSupportedPolicyTypes();
132 return new ResponseEntity<>(toPolicyTypeIdsJson(types), HttpStatus.OK);
133 } catch (ServiceException e) {
134 return new ResponseEntity<>(e.toString(), HttpStatus.NOT_FOUND);
140 @GetMapping("/policy")
141 @ApiOperation(value = "Returns a policy configuration") //
144 @ApiResponse(code = 200, message = "Policy found", response = Object.class), //
145 @ApiResponse(code = 404, message = "Policy is not found")} //
147 public ResponseEntity<String> getPolicy( //
148 @RequestParam(name = "instance", required = true) String instance) {
150 Policy p = policies.getPolicy(instance);
151 return new ResponseEntity<>(p.json(), HttpStatus.OK);
152 } catch (ServiceException e) {
153 return new ResponseEntity<>(e.getMessage(), HttpStatus.NOT_FOUND);
157 @DeleteMapping("/policy")
158 @ApiOperation(value = "Delete a policy", response = Object.class)
161 @ApiResponse(code = 204, message = "Policy deleted", response = Object.class),
162 @ApiResponse(code = 404, message = "Policy is not found", response = String.class),
163 @ApiResponse(code = 423, message = "RIC is locked", response = String.class)})
164 public Mono<ResponseEntity<Object>> deletePolicy( //
165 @RequestParam(name = "instance", required = true) String id) {
168 policy = policies.getPolicy(id);
169 keepServiceAlive(policy.ownerServiceName());
170 if (policy.ric().getState() != Ric.RicState.IDLE) {
171 return Mono.just(new ResponseEntity<>("Busy, recovering", HttpStatus.LOCKED));
173 Ric ric = policy.ric();
174 return ric.getLock().lock(LockType.SHARED) // //
175 .flatMap(lock -> a1ClientFactory.createA1Client(policy.ric())) //
176 .doOnNext(notUsed -> policies.remove(policy)) //
177 .flatMap(client -> client.deletePolicy(policy)) //
178 .doOnNext(notUsed -> ric.getLock().unlockBlocking()) //
179 .doOnError(notUsed -> ric.getLock().unlockBlocking()) //
180 .flatMap(notUsed -> Mono.just(new ResponseEntity<>(HttpStatus.NO_CONTENT)));
181 } catch (ServiceException e) {
182 return Mono.just(new ResponseEntity<>(HttpStatus.NOT_FOUND));
186 @PutMapping(path = "/policy")
187 @ApiOperation(value = "Put a policy", response = String.class)
190 @ApiResponse(code = 201, message = "Policy created", response = Object.class), //
191 @ApiResponse(code = 200, message = "Policy updated", response = Object.class), //
192 @ApiResponse(code = 423, message = "RIC is locked", response = String.class), //
193 @ApiResponse(code = 404, message = "RIC or policy type is not found", response = String.class), //
194 @ApiResponse(code = 405, message = "Change is not allowed", response = String.class)})
195 public Mono<ResponseEntity<Object>> putPolicy( //
196 @RequestParam(name = "type", required = true) String typeName, //
197 @RequestParam(name = "instance", required = true) String instanceId, //
198 @RequestParam(name = "ric", required = true) String ricName, //
199 @RequestParam(name = "service", required = true) String service, //
200 @RequestBody Object jsonBody) {
202 String jsonString = gson.toJson(jsonBody);
203 Ric ric = rics.get(ricName);
204 PolicyType type = policyTypes.get(typeName);
205 keepServiceAlive(service);
206 if (ric != null && type != null && ric.getState() == Ric.RicState.IDLE) {
207 Policy policy = ImmutablePolicy.builder() //
212 .ownerServiceName(service) //
213 .lastModified(getTimeStampUtc()) //
216 final boolean isCreate = this.policies.get(policy.id()) == null;
218 return ric.getLock().lock(LockType.SHARED) //
219 .flatMap(p -> validateModifiedPolicy(policy)) //
220 .flatMap(notUsed -> a1ClientFactory.createA1Client(ric)) //
221 .flatMap(client -> client.putPolicy(policy)) //
222 .doOnNext(notUsed -> policies.put(policy)) //
223 .doOnNext(notUsed -> ric.getLock().unlockBlocking()) //
224 .doOnError(t -> ric.getLock().unlockBlocking()) //
225 .flatMap(notUsed -> Mono.just(new ResponseEntity<>(isCreate ? HttpStatus.CREATED : HttpStatus.OK))) //
226 .onErrorResume(t -> Mono.just(new ResponseEntity<>(t.getMessage(), HttpStatus.METHOD_NOT_ALLOWED)));
229 return ric == null || type == null ? Mono.just(new ResponseEntity<>(HttpStatus.NOT_FOUND))
230 : Mono.just(new ResponseEntity<>(HttpStatus.LOCKED)); // Recovering
233 private Mono<Object> validateModifiedPolicy(Policy policy) {
234 // Check that ric is not updated
235 Policy current = this.policies.get(policy.id());
236 if (current != null && !current.ric().name().equals(policy.ric().name())) {
237 return Mono.error(new Exception("Policy cannot change RIC, policyId: " + current.id() + //
238 ", RIC name: " + current.ric().name() + //
239 ", new name: " + policy.ric().name()));
241 return Mono.just("OK");
244 @GetMapping("/policies")
245 @ApiOperation(value = "Query policies")
248 @ApiResponse(code = 200, message = "Policies", response = PolicyInfo.class, responseContainer = "List"),
249 @ApiResponse(code = 404, message = "RIC or type not found", response = String.class)})
250 public ResponseEntity<String> getPolicies( //
251 @RequestParam(name = "type", required = false) String type, //
252 @RequestParam(name = "ric", required = false) String ric, //
253 @RequestParam(name = "service", required = false) String service) //
255 if ((type != null && this.policyTypes.get(type) == null)) {
256 return new ResponseEntity<>("Policy type not found", HttpStatus.NOT_FOUND);
258 if ((ric != null && this.rics.get(ric) == null)) {
259 return new ResponseEntity<>("RIC not found", HttpStatus.NOT_FOUND);
261 synchronized (policies) {
262 Collection<Policy> result = null;
265 result = policies.getForType(type);
266 result = filter(result, null, ric, service);
267 } else if (service != null) {
268 result = policies.getForService(service);
269 result = filter(result, type, ric, null);
270 } else if (ric != null) {
271 result = filter(policies.getForRic(ric), type, null, service);
273 result = policies.getAll();
278 policiesJson = policiesToJson(result);
279 } catch (ServiceException e) {
280 return new ResponseEntity<>(e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
282 return new ResponseEntity<>(policiesJson, HttpStatus.OK);
286 @GetMapping("/policy_status")
287 @ApiOperation(value = "Returns a policy status") //
290 @ApiResponse(code = 200, message = "Policy status", response = Object.class), //
291 @ApiResponse(code = 404, message = "Policy is not found", response = String.class)} //
293 public Mono<ResponseEntity<String>> getPolicyStatus( //
294 @RequestParam(name = "instance", required = true) String instance) {
296 Policy policy = policies.getPolicy(instance);
298 return a1ClientFactory.createA1Client(policy.ric()) //
299 .flatMap(client -> client.getPolicyStatus(policy)) //
300 .flatMap(status -> Mono.just(new ResponseEntity<>(status, HttpStatus.OK)));
301 } catch (ServiceException e) {
302 return Mono.just(new ResponseEntity<>(e.getMessage(), HttpStatus.NOT_FOUND));
306 private void keepServiceAlive(String name) {
307 Service s = this.services.get(name);
313 private boolean include(String filter, String value) {
314 return filter == null || value.equals(filter);
317 private Collection<Policy> filter(Collection<Policy> collection, String type, String ric, String service) {
318 if (type == null && ric == null && service == null) {
321 List<Policy> filtered = new ArrayList<>();
322 for (Policy p : collection) {
323 if (include(type, p.type().name()) && include(ric, p.ric().name())
324 && include(service, p.ownerServiceName())) {
331 private String policiesToJson(Collection<Policy> policies) throws ServiceException {
332 List<PolicyInfo> v = new ArrayList<>(policies.size());
333 for (Policy p : policies) {
334 PolicyInfo policyInfo = new PolicyInfo();
335 policyInfo.id = p.id();
336 policyInfo.json = fromJson(p.json());
337 policyInfo.ric = p.ric().name();
338 policyInfo.type = p.type().name();
339 policyInfo.service = p.ownerServiceName();
340 policyInfo.lastModified = p.lastModified();
341 if (!policyInfo.validate()) {
342 throw new ServiceException("BUG, all fields must be set");
346 return gson.toJson(v);
349 private Object fromJson(String jsonStr) {
350 return gson.fromJson(jsonStr, Object.class);
353 private String toPolicyTypeSchemasJson(Collection<PolicyType> types) {
354 StringBuilder result = new StringBuilder();
356 boolean first = true;
357 for (PolicyType t : types) {
362 result.append(t.schema());
365 return result.toString();
368 private String toPolicyTypeIdsJson(Collection<PolicyType> types) {
369 List<String> v = new ArrayList<>(types.size());
370 for (PolicyType t : types) {
373 return gson.toJson(v);
376 private String getTimeStampUtc() {
377 return java.time.Instant.now().toString();