Merge "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             logger.debug("Request rejected, {}", e.getMessage());
290             return Mono.error(e);
291         }
292         return Mono.just("OK");
293     }
294
295     private Mono<Object> checkSupportedType(Ric ric, PolicyType type) {
296         if (!ric.isSupportingType(type.name())) {
297             logger.debug("Request rejected, type not supported, RIC: {}", ric);
298             RejectionException e = new RejectionException(
299                 "Type: " + type.name() + " not supported by RIC: " + ric.name(), HttpStatus.NOT_FOUND);
300             return Mono.error(e);
301         }
302         return Mono.just("OK");
303     }
304
305     private Mono<Object> assertRicStateIdle(Ric ric) {
306         if (ric.getState() == Ric.RicState.AVAILABLE) {
307             return Mono.just("OK");
308         } else {
309             logger.debug("Request rejected RIC not IDLE, ric: {}", ric);
310             RejectionException e = new RejectionException(
311                 "Ric is not operational, RIC name: " + ric.name() + ", state: " + ric.getState(), HttpStatus.LOCKED);
312             return Mono.error(e);
313         }
314     }
315
316     @GetMapping("/policies")
317     @ApiOperation(value = "Query policies")
318     @ApiResponses(
319         value = {
320             @ApiResponse(code = 200, message = "Policies", response = PolicyInfo.class, responseContainer = "List"),
321             @ApiResponse(code = 404, message = "RIC or type not found", response = String.class)})
322     public ResponseEntity<String> getPolicies( //
323         @ApiParam(name = "type", required = false, value = "The name of the policy type to get policies for.") //
324         @RequestParam(name = "type", required = false) String type, //
325         @ApiParam(name = "ric", required = false, value = "The name of the Near-RT RIC to get policies for.") //
326         @RequestParam(name = "ric", required = false) String ric, //
327         @ApiParam(name = "service", required = false, value = "The name of the service to get policies for.") //
328         @RequestParam(name = "service", required = false) String service) //
329     {
330         if ((type != null && this.policyTypes.get(type) == null)) {
331             return new ResponseEntity<>("Policy type not found", HttpStatus.NOT_FOUND);
332         }
333         if ((ric != null && this.rics.get(ric) == null)) {
334             return new ResponseEntity<>("RIC not found", HttpStatus.NOT_FOUND);
335         }
336
337         String filteredPolicies = policiesToJson(filter(type, ric, service));
338         return new ResponseEntity<>(filteredPolicies, HttpStatus.OK);
339     }
340
341     @GetMapping("/policy_ids")
342     @ApiOperation(value = "Query policies, only IDs returned")
343     @ApiResponses(
344         value = {@ApiResponse(code = 200, message = "Policy ids", response = String.class, responseContainer = "List"),
345             @ApiResponse(code = 404, message = "RIC or type not found", response = String.class)})
346     public ResponseEntity<String> getPolicyIds( //
347         @ApiParam(name = "type", required = false, value = "The name of the policy type to get policies for.") //
348         @RequestParam(name = "type", required = false) String type, //
349         @ApiParam(name = "ric", required = false, value = "The name of the Near-RT RIC to get policies for.") //
350         @RequestParam(name = "ric", required = false) String ric, //
351         @ApiParam(name = "service", required = false, value = "The name of the service to get policies for.") //
352         @RequestParam(name = "service", required = false) String service) //
353     {
354         if ((type != null && this.policyTypes.get(type) == null)) {
355             return new ResponseEntity<>("Policy type not found", HttpStatus.NOT_FOUND);
356         }
357         if ((ric != null && this.rics.get(ric) == null)) {
358             return new ResponseEntity<>("RIC not found", HttpStatus.NOT_FOUND);
359         }
360
361         String policyIdsJson = toPolicyIdsJson(filter(type, ric, service));
362         return new ResponseEntity<>(policyIdsJson, HttpStatus.OK);
363     }
364
365     @GetMapping("/policy_status")
366     @ApiOperation(value = "Returns a policy status") //
367     @ApiResponses(
368         value = { //
369             @ApiResponse(code = 200, message = "Policy status", response = Object.class), //
370             @ApiResponse(code = 404, message = "Policy is not found", response = String.class)} //
371     )
372     public Mono<ResponseEntity<String>> getPolicyStatus( //
373         @ApiParam(name = "id", required = true, value = "The ID of the policy.") @RequestParam(
374             name = "id", //
375             required = true) String id) {
376         try {
377             Policy policy = policies.getPolicy(id);
378
379             return a1ClientFactory.createA1Client(policy.ric()) //
380                 .flatMap(client -> client.getPolicyStatus(policy)) //
381                 .flatMap(status -> Mono.just(new ResponseEntity<>(status, HttpStatus.OK)))
382                 .onErrorResume(this::handleException);
383         } catch (ServiceException e) {
384             return Mono.just(new ResponseEntity<>(e.getMessage(), HttpStatus.NOT_FOUND));
385         }
386     }
387
388     private void keepServiceAlive(String name) {
389         Service s = this.services.get(name);
390         if (s != null) {
391             s.keepAlive();
392         }
393     }
394
395     private boolean include(String filter, String value) {
396         return filter == null || value.equals(filter);
397     }
398
399     private Collection<Policy> filter(Collection<Policy> collection, String type, String ric, String service) {
400         if (type == null && ric == null && service == null) {
401             return collection;
402         }
403         List<Policy> filtered = new ArrayList<>();
404         for (Policy p : collection) {
405             if (include(type, p.type().name()) && include(ric, p.ric().name())
406                 && include(service, p.ownerServiceName())) {
407                 filtered.add(p);
408             }
409         }
410         return filtered;
411     }
412
413     private Collection<Policy> filter(String type, String ric, String service) {
414         if (type != null) {
415             return filter(policies.getForType(type), null, ric, service);
416         } else if (service != null) {
417             return filter(policies.getForService(service), type, ric, null);
418         } else if (ric != null) {
419             return filter(policies.getForRic(ric), type, null, service);
420         } else {
421             return policies.getAll();
422         }
423     }
424
425     private String policiesToJson(Collection<Policy> policies) {
426         List<PolicyInfo> v = new ArrayList<>(policies.size());
427         for (Policy p : policies) {
428             PolicyInfo policyInfo = new PolicyInfo();
429             policyInfo.id = p.id();
430             policyInfo.json = fromJson(p.json());
431             policyInfo.ric = p.ric().name();
432             policyInfo.type = p.type().name();
433             policyInfo.service = p.ownerServiceName();
434             policyInfo.lastModified = p.lastModified();
435             if (!policyInfo.validate()) {
436                 logger.error("BUG, all fields must be set");
437             }
438             v.add(policyInfo);
439         }
440         return gson.toJson(v);
441     }
442
443     private Object fromJson(String jsonStr) {
444         return gson.fromJson(jsonStr, Object.class);
445     }
446
447     private String toPolicyTypeSchemasJson(Collection<PolicyType> types) {
448         StringBuilder result = new StringBuilder();
449         result.append("[");
450         boolean first = true;
451         for (PolicyType t : types) {
452             if (!first) {
453                 result.append(",");
454             }
455             first = false;
456             result.append(t.schema());
457         }
458         result.append("]");
459         return result.toString();
460     }
461
462     private String toPolicyTypeIdsJson(Collection<PolicyType> types) {
463         List<String> v = new ArrayList<>(types.size());
464         for (PolicyType t : types) {
465             v.add(t.name());
466         }
467         return gson.toJson(v);
468     }
469
470     private String toPolicyIdsJson(Collection<Policy> policies) {
471         List<String> v = new ArrayList<>(policies.size());
472         for (Policy p : policies) {
473             v.add(p.id());
474         }
475         return gson.toJson(v);
476     }
477
478     private String getTimeStampUtc() {
479         return java.time.Instant.now().toString();
480     }
481
482 }