Add description to parameters in the remaining controllers
[nonrtric.git] / policy-agent / src / main / java / org / oransc / policyagent / controllers / PolicyController.java
1 /*-
2  * ========================LICENSE_START=================================
3  * O-RAN-SC
4  * %%
5  * Copyright (C) 2019 Nordix Foundation
6  * %%
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
10  *
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  *
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===================================
19  */
20
21 package org.oransc.policyagent.controllers;
22
23 import com.google.gson.Gson;
24 import com.google.gson.GsonBuilder;
25
26 import io.swagger.annotations.Api;
27 import io.swagger.annotations.ApiOperation;
28 import io.swagger.annotations.ApiParam;
29 import io.swagger.annotations.ApiResponse;
30 import io.swagger.annotations.ApiResponses;
31
32 import java.lang.invoke.MethodHandles;
33 import java.util.ArrayList;
34 import java.util.Collection;
35 import java.util.List;
36
37 import lombok.Getter;
38
39 import org.oransc.policyagent.clients.A1ClientFactory;
40 import org.oransc.policyagent.exceptions.ServiceException;
41 import org.oransc.policyagent.repository.ImmutablePolicy;
42 import org.oransc.policyagent.repository.Lock.LockType;
43 import org.oransc.policyagent.repository.Policies;
44 import org.oransc.policyagent.repository.Policy;
45 import org.oransc.policyagent.repository.PolicyType;
46 import org.oransc.policyagent.repository.PolicyTypes;
47 import org.oransc.policyagent.repository.Ric;
48 import org.oransc.policyagent.repository.Rics;
49 import org.oransc.policyagent.repository.Service;
50 import org.oransc.policyagent.repository.Services;
51 import org.slf4j.Logger;
52 import org.slf4j.LoggerFactory;
53 import org.springframework.beans.factory.annotation.Autowired;
54 import org.springframework.http.HttpStatus;
55 import org.springframework.http.ResponseEntity;
56 import org.springframework.web.bind.annotation.DeleteMapping;
57 import org.springframework.web.bind.annotation.GetMapping;
58 import org.springframework.web.bind.annotation.PutMapping;
59 import org.springframework.web.bind.annotation.RequestBody;
60 import org.springframework.web.bind.annotation.RequestParam;
61 import org.springframework.web.bind.annotation.RestController;
62 import org.springframework.web.reactive.function.client.WebClientResponseException;
63 import reactor.core.publisher.Mono;
64
65 @RestController
66 @Api(tags = "A1 Policy Management")
67 public class PolicyController {
68
69     public static class RejectionException extends Exception {
70         private static final long serialVersionUID = 1L;
71         @Getter
72         private final HttpStatus status;
73
74         public RejectionException(String message, HttpStatus status) {
75             super(message);
76             this.status = status;
77         }
78     }
79
80     @Autowired
81     private Rics rics;
82     @Autowired
83     private PolicyTypes policyTypes;
84     @Autowired
85     private Policies policies;
86     @Autowired
87     private A1ClientFactory a1ClientFactory;
88     @Autowired
89     private Services services;
90
91     private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
92     private static Gson gson = new GsonBuilder() //
93         .serializeNulls() //
94         .create(); //
95
96     @GetMapping("/policy_schemas")
97     @ApiOperation(value = "Returns policy type schema definitions")
98     @ApiResponses(
99         value = {
100             @ApiResponse(code = 200, message = "Policy schemas", response = Object.class, responseContainer = "List"), //
101             @ApiResponse(code = 404, message = "RIC is not found", response = String.class)})
102     public ResponseEntity<String> getPolicySchemas( //
103         @ApiParam(name = "ric", required = false, value = "The name of the Near-RT RIC to get the definitions for.") //
104         @RequestParam(name = "ric", required = false) String ricName) {
105         if (ricName == null) {
106             Collection<PolicyType> types = this.policyTypes.getAll();
107             return new ResponseEntity<>(toPolicyTypeSchemasJson(types), HttpStatus.OK);
108         } else {
109             try {
110                 Collection<PolicyType> types = rics.getRic(ricName).getSupportedPolicyTypes();
111                 return new ResponseEntity<>(toPolicyTypeSchemasJson(types), HttpStatus.OK);
112             } catch (ServiceException e) {
113                 return new ResponseEntity<>(e.toString(), HttpStatus.NOT_FOUND);
114             }
115         }
116     }
117
118     @GetMapping("/policy_schema")
119     @ApiOperation(value = "Returns one policy type schema definition")
120     @ApiResponses(
121         value = { //
122             @ApiResponse(code = 200, message = "Policy schema", response = Object.class),
123             @ApiResponse(code = 404, message = "RIC is not found", response = String.class)})
124     public ResponseEntity<String> getPolicySchema( //
125         @ApiParam(name = "id", required = true, value = "The ID of the policy type to get the definition for.") //
126         @RequestParam(name = "id", required = true) String id) {
127         try {
128             PolicyType type = policyTypes.getType(id);
129             return new ResponseEntity<>(type.schema(), HttpStatus.OK);
130         } catch (ServiceException e) {
131             return new ResponseEntity<>(e.toString(), HttpStatus.NOT_FOUND);
132         }
133     }
134
135     @GetMapping("/policy_types")
136     @ApiOperation(value = "Query policy type names")
137     @ApiResponses(
138         value = {
139             @ApiResponse(
140                 code = 200,
141                 message = "Policy type names",
142                 response = String.class,
143                 responseContainer = "List"),
144             @ApiResponse(code = 404, message = "RIC is not found", response = String.class)})
145     public ResponseEntity<String> getPolicyTypes( //
146         @ApiParam(name = "ric", required = false, value = "The name of the Near-RT RIC to get types for.") //
147         @RequestParam(name = "ric", required = false) String ricName) {
148         if (ricName == null) {
149             Collection<PolicyType> types = this.policyTypes.getAll();
150             return new ResponseEntity<>(toPolicyTypeIdsJson(types), HttpStatus.OK);
151         } else {
152             try {
153                 Collection<PolicyType> types = rics.getRic(ricName).getSupportedPolicyTypes();
154                 return new ResponseEntity<>(toPolicyTypeIdsJson(types), HttpStatus.OK);
155             } catch (ServiceException e) {
156                 return new ResponseEntity<>(e.toString(), HttpStatus.NOT_FOUND);
157             }
158         }
159     }
160
161     @GetMapping("/policy")
162     @ApiOperation(value = "Returns a policy configuration") //
163     @ApiResponses(
164         value = { //
165             @ApiResponse(code = 200, message = "Policy found", response = Object.class), //
166             @ApiResponse(code = 404, message = "Policy is not found")} //
167     )
168     public ResponseEntity<String> getPolicy( //
169         @ApiParam(name = "id", required = true, value = "The ID of the policy instance.") //
170         @RequestParam(name = "id", required = true) String id) {
171         try {
172             Policy p = policies.getPolicy(id);
173             return new ResponseEntity<>(p.json(), HttpStatus.OK);
174         } catch (ServiceException e) {
175             return new ResponseEntity<>(e.getMessage(), HttpStatus.NOT_FOUND);
176         }
177     }
178
179     @DeleteMapping("/policy")
180     @ApiOperation(value = "Delete a policy", response = Object.class)
181     @ApiResponses(
182         value = { //
183             @ApiResponse(code = 204, message = "Policy deleted", response = Object.class),
184             @ApiResponse(code = 404, message = "Policy is not found", response = String.class),
185             @ApiResponse(code = 423, message = "RIC is not operational", response = String.class)})
186     public Mono<ResponseEntity<Object>> deletePolicy( //
187         @ApiParam(name = "id", required = true, value = "The ID of the policy instance.") //
188         @RequestParam(name = "id", required = true) String id) {
189         try {
190             Policy policy = policies.getPolicy(id);
191             keepServiceAlive(policy.ownerServiceName());
192             Ric ric = policy.ric();
193             return ric.getLock().lock(LockType.SHARED) //
194                 .flatMap(notUsed -> assertRicStateIdle(ric)) //
195                 .flatMap(notUsed -> a1ClientFactory.createA1Client(policy.ric())) //
196                 .doOnNext(notUsed -> policies.remove(policy)) //
197                 .flatMap(client -> client.deletePolicy(policy)) //
198                 .doOnNext(notUsed -> ric.getLock().unlockBlocking()) //
199                 .doOnError(notUsed -> ric.getLock().unlockBlocking()) //
200                 .flatMap(notUsed -> Mono.just(new ResponseEntity<>(HttpStatus.NO_CONTENT)))
201                 .onErrorResume(this::handleException);
202         } catch (ServiceException e) {
203             return Mono.just(new ResponseEntity<>(HttpStatus.NOT_FOUND));
204         }
205     }
206
207     @PutMapping(path = "/policy")
208     @ApiOperation(value = "Put a policy", response = String.class)
209     @ApiResponses(
210         value = { //
211             @ApiResponse(code = 201, message = "Policy created", response = Object.class), //
212             @ApiResponse(code = 200, message = "Policy updated", response = Object.class), //
213             @ApiResponse(code = 423, message = "RIC is not operational", response = String.class), //
214             @ApiResponse(code = 404, message = "RIC or policy type is not found", response = String.class) //
215         })
216     public Mono<ResponseEntity<Object>> putPolicy( //
217         @ApiParam(name = "type", required = false, value = "The name of the policy type.") //
218         @RequestParam(name = "type", required = false, defaultValue = "") String typeName, //
219         @ApiParam(name = "id", required = true, value = "The ID of the policy instance.") //
220         @RequestParam(name = "id", required = true) String instanceId, //
221         @ApiParam(name = "ric", required = true, value = "The name of the Near-RT RIC where the policy will be " + //
222             "created.") //
223         @RequestParam(name = "ric", required = true) String ricName, //
224         @ApiParam(name = "service", required = true, value = "The name of the service creating the policy.") //
225         @RequestParam(name = "service", required = true) String service, //
226         @ApiParam(name = "transient", required = false, value = "If the policy is transient or not (boolean " + //
227             "defaulted to false). A policy is transient if it will be forgotten when the service needs to " + //
228             "reconnect to the Near-RT RIC.") //
229         @RequestParam(name = "transient", required = false, defaultValue = "false") boolean isTransient, //
230         @RequestBody Object jsonBody) {
231
232         String jsonString = gson.toJson(jsonBody);
233         Ric ric = rics.get(ricName);
234         PolicyType type = policyTypes.get(typeName);
235         keepServiceAlive(service);
236         if (ric == null || type == null) {
237             return Mono.just(new ResponseEntity<>(HttpStatus.NOT_FOUND));
238         }
239         Policy policy = ImmutablePolicy.builder() //
240             .id(instanceId) //
241             .json(jsonString) //
242             .type(type) //
243             .ric(ric) //
244             .ownerServiceName(service) //
245             .lastModified(getTimeStampUtc()) //
246             .isTransient(isTransient) //
247             .build();
248
249         final boolean isCreate = this.policies.get(policy.id()) == null;
250
251         return ric.getLock().lock(LockType.SHARED) //
252             .flatMap(notUsed -> assertRicStateIdle(ric)) //
253             .flatMap(notUsed -> checkSupportedType(ric, type)) //
254             .flatMap(notUsed -> validateModifiedPolicy(policy)) //
255             .flatMap(notUsed -> a1ClientFactory.createA1Client(ric)) //
256             .flatMap(client -> client.putPolicy(policy)) //
257             .doOnNext(notUsed -> policies.put(policy)) //
258             .doOnNext(notUsed -> ric.getLock().unlockBlocking()) //
259             .doOnError(trowable -> ric.getLock().unlockBlocking()) //
260             .flatMap(notUsed -> Mono.just(new ResponseEntity<>(isCreate ? HttpStatus.CREATED : HttpStatus.OK))) //
261             .onErrorResume(this::handleException);
262     }
263
264     @SuppressWarnings({"unchecked"})
265     private <T> Mono<ResponseEntity<T>> createResponseEntity(String message, HttpStatus status) {
266         ResponseEntity<T> re = new ResponseEntity<>((T) message, status);
267         return Mono.just(re);
268     }
269
270     private <T> Mono<ResponseEntity<T>> handleException(Throwable throwable) {
271         if (throwable instanceof WebClientResponseException) {
272             WebClientResponseException e = (WebClientResponseException) throwable;
273             return createResponseEntity(e.getResponseBodyAsString(), e.getStatusCode());
274         } else if (throwable instanceof RejectionException) {
275             RejectionException e = (RejectionException) throwable;
276             return createResponseEntity(e.getMessage(), e.getStatus());
277         } else {
278             return createResponseEntity(throwable.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
279         }
280     }
281
282     private Mono<Object> validateModifiedPolicy(Policy policy) {
283         // Check that ric is not updated
284         Policy current = this.policies.get(policy.id());
285         if (current != null && !current.ric().name().equals(policy.ric().name())) {
286             RejectionException e = new RejectionException("Policy cannot change RIC, policyId: " + current.id() + //
287                 ", RIC name: " + current.ric().name() + //
288                 ", new name: " + policy.ric().name(), HttpStatus.CONFLICT);
289             return Mono.error(e);
290         }
291         return Mono.just("OK");
292     }
293
294     private Mono<Object> checkSupportedType(Ric ric, PolicyType type) {
295         if (!ric.isSupportingType(type.name())) {
296             RejectionException e = new RejectionException(
297                 "Type: " + type.name() + " not supported by RIC: " + ric.name(), HttpStatus.NOT_FOUND);
298             return Mono.error(e);
299         }
300         return Mono.just("OK");
301     }
302
303     private Mono<Object> assertRicStateIdle(Ric ric) {
304         if (ric.getState() == Ric.RicState.AVAILABLE) {
305             return Mono.just("OK");
306         } else {
307             RejectionException e = new RejectionException(
308                 "Ric is not operational, RIC name: " + ric.name() + ", state: " + ric.getState(), HttpStatus.LOCKED);
309             return Mono.error(e);
310         }
311     }
312
313     @GetMapping("/policies")
314     @ApiOperation(value = "Query policies")
315     @ApiResponses(
316         value = {
317             @ApiResponse(code = 200, message = "Policies", response = PolicyInfo.class, responseContainer = "List"),
318             @ApiResponse(code = 404, message = "RIC or type not found", response = String.class)})
319     public ResponseEntity<String> getPolicies( //
320         @ApiParam(name = "type", required = false, value = "The name of the policy type to get policies for.") //
321         @RequestParam(name = "type", required = false) String type, //
322         @ApiParam(name = "ric", required = false, value = "The name of the Near-RT RIC to get policies for.") //
323         @RequestParam(name = "ric", required = false) String ric, //
324         @ApiParam(name = "service", required = false, value = "The name of the service to get policies for.") //
325         @RequestParam(name = "service", required = false) String service) //
326     {
327         if ((type != null && this.policyTypes.get(type) == null)) {
328             return new ResponseEntity<>("Policy type not found", HttpStatus.NOT_FOUND);
329         }
330         if ((ric != null && this.rics.get(ric) == null)) {
331             return new ResponseEntity<>("RIC not found", HttpStatus.NOT_FOUND);
332         }
333
334         String filteredPolicies = policiesToJson(filter(type, ric, service));
335         return new ResponseEntity<>(filteredPolicies, HttpStatus.OK);
336     }
337
338     @GetMapping("/policy_ids")
339     @ApiOperation(value = "Query policies, only IDs returned")
340     @ApiResponses(
341         value = {@ApiResponse(code = 200, message = "Policy ids", response = String.class, responseContainer = "List"),
342             @ApiResponse(code = 404, message = "RIC or type not found", response = String.class)})
343     public ResponseEntity<String> getPolicyIds( //
344         @ApiParam(name = "type", required = false, value = "The name of the policy type to get policies for.") //
345         @RequestParam(name = "type", required = false) String type, //
346         @ApiParam(name = "ric", required = false, value = "The name of the Near-RT RIC to get policies for.") //
347         @RequestParam(name = "ric", required = false) String ric, //
348         @ApiParam(name = "service", required = false, value = "The name of the service to get policies for.") //
349         @RequestParam(name = "service", required = false) String service) //
350     {
351         if ((type != null && this.policyTypes.get(type) == null)) {
352             return new ResponseEntity<>("Policy type not found", HttpStatus.NOT_FOUND);
353         }
354         if ((ric != null && this.rics.get(ric) == null)) {
355             return new ResponseEntity<>("RIC not found", HttpStatus.NOT_FOUND);
356         }
357
358         String policyIdsJson = toPolicyIdsJson(filter(type, ric, service));
359         return new ResponseEntity<>(policyIdsJson, HttpStatus.OK);
360     }
361
362     @GetMapping("/policy_status")
363     @ApiOperation(value = "Returns a policy status") //
364     @ApiResponses(
365         value = { //
366             @ApiResponse(code = 200, message = "Policy status", response = Object.class), //
367             @ApiResponse(code = 404, message = "Policy is not found", response = String.class)} //
368     )
369     public Mono<ResponseEntity<String>> getPolicyStatus( //
370         @ApiParam(name = "id", required = true, value = "The ID of the policy.") @RequestParam(
371             name = "id", //
372             required = true) String id) {
373         try {
374             Policy policy = policies.getPolicy(id);
375
376             return a1ClientFactory.createA1Client(policy.ric()) //
377                 .flatMap(client -> client.getPolicyStatus(policy)) //
378                 .flatMap(status -> Mono.just(new ResponseEntity<>(status, HttpStatus.OK)))
379                 .onErrorResume(this::handleException);
380         } catch (ServiceException e) {
381             return Mono.just(new ResponseEntity<>(e.getMessage(), HttpStatus.NOT_FOUND));
382         }
383     }
384
385     private void keepServiceAlive(String name) {
386         Service s = this.services.get(name);
387         if (s != null) {
388             s.keepAlive();
389         }
390     }
391
392     private boolean include(String filter, String value) {
393         return filter == null || value.equals(filter);
394     }
395
396     private Collection<Policy> filter(Collection<Policy> collection, String type, String ric, String service) {
397         if (type == null && ric == null && service == null) {
398             return collection;
399         }
400         List<Policy> filtered = new ArrayList<>();
401         for (Policy p : collection) {
402             if (include(type, p.type().name()) && include(ric, p.ric().name())
403                 && include(service, p.ownerServiceName())) {
404                 filtered.add(p);
405             }
406         }
407         return filtered;
408     }
409
410     private Collection<Policy> filter(String type, String ric, String service) {
411         if (type != null) {
412             return filter(policies.getForType(type), null, ric, service);
413         } else if (service != null) {
414             return filter(policies.getForService(service), type, ric, null);
415         } else if (ric != null) {
416             return filter(policies.getForRic(ric), type, null, service);
417         } else {
418             return policies.getAll();
419         }
420     }
421
422     private String policiesToJson(Collection<Policy> policies) {
423         List<PolicyInfo> v = new ArrayList<>(policies.size());
424         for (Policy p : policies) {
425             PolicyInfo policyInfo = new PolicyInfo();
426             policyInfo.id = p.id();
427             policyInfo.json = fromJson(p.json());
428             policyInfo.ric = p.ric().name();
429             policyInfo.type = p.type().name();
430             policyInfo.service = p.ownerServiceName();
431             policyInfo.lastModified = p.lastModified();
432             if (!policyInfo.validate()) {
433                 logger.error("BUG, all fields must be set");
434             }
435             v.add(policyInfo);
436         }
437         return gson.toJson(v);
438     }
439
440     private Object fromJson(String jsonStr) {
441         return gson.fromJson(jsonStr, Object.class);
442     }
443
444     private String toPolicyTypeSchemasJson(Collection<PolicyType> types) {
445         StringBuilder result = new StringBuilder();
446         result.append("[");
447         boolean first = true;
448         for (PolicyType t : types) {
449             if (!first) {
450                 result.append(",");
451             }
452             first = false;
453             result.append(t.schema());
454         }
455         result.append("]");
456         return result.toString();
457     }
458
459     private String toPolicyTypeIdsJson(Collection<PolicyType> types) {
460         List<String> v = new ArrayList<>(types.size());
461         for (PolicyType t : types) {
462             v.add(t.name());
463         }
464         return gson.toJson(v);
465     }
466
467     private String toPolicyIdsJson(Collection<Policy> policies) {
468         List<String> v = new ArrayList<>(policies.size());
469         for (Policy p : policies) {
470             v.add(p.id());
471         }
472         return gson.toJson(v);
473     }
474
475     private String getTimeStampUtc() {
476         return java.time.Instant.now().toString();
477     }
478
479 }