Merge "Add description to parameters in policy controller"
[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(@ApiParam(name = "ric", required = false, value = "The name of " +//
103         "the Near-RT RIC to get the definitions for.")@RequestParam(name = "ric", required = false) String ricName) {
104         if (ricName == null) {
105             Collection<PolicyType> types = this.policyTypes.getAll();
106             return new ResponseEntity<>(toPolicyTypeSchemasJson(types), HttpStatus.OK);
107         } else {
108             try {
109                 Collection<PolicyType> types = rics.getRic(ricName).getSupportedPolicyTypes();
110                 return new ResponseEntity<>(toPolicyTypeSchemasJson(types), HttpStatus.OK);
111             } catch (ServiceException e) {
112                 return new ResponseEntity<>(e.toString(), HttpStatus.NOT_FOUND);
113             }
114         }
115     }
116
117     @GetMapping("/policy_schema")
118     @ApiOperation(value = "Returns one policy type schema definition")
119     @ApiResponses(
120         value = { //
121             @ApiResponse(code = 200, message = "Policy schema", response = Object.class),
122             @ApiResponse(code = 404, message = "RIC is not found", response = String.class)})
123     public ResponseEntity<String> getPolicySchema(@ApiParam(name = "id", required = true, value = "The ID of the " +//
124         "policy type to get the definition for.")@RequestParam(name = "id", required = true) String id) {
125         try {
126             PolicyType type = policyTypes.getType(id);
127             return new ResponseEntity<>(type.schema(), HttpStatus.OK);
128         } catch (ServiceException e) {
129             return new ResponseEntity<>(e.toString(), HttpStatus.NOT_FOUND);
130         }
131     }
132
133     @GetMapping("/policy_types")
134     @ApiOperation(value = "Query policy type names")
135     @ApiResponses(
136         value = {
137             @ApiResponse(
138                 code = 200,
139                 message = "Policy type names",
140                 response = String.class,
141                 responseContainer = "List"),
142             @ApiResponse(code = 404, message = "RIC is not found", response = String.class)})
143     public ResponseEntity<String> getPolicyTypes(@ApiParam(name = "ric", required = false, value = "The name of " +//
144         "the Near-RT RIC to get types for.")@RequestParam(name = "ric", required = false) String ricName) {
145         if (ricName == null) {
146             Collection<PolicyType> types = this.policyTypes.getAll();
147             return new ResponseEntity<>(toPolicyTypeIdsJson(types), HttpStatus.OK);
148         } else {
149             try {
150                 Collection<PolicyType> types = rics.getRic(ricName).getSupportedPolicyTypes();
151                 return new ResponseEntity<>(toPolicyTypeIdsJson(types), HttpStatus.OK);
152             } catch (ServiceException e) {
153                 return new ResponseEntity<>(e.toString(), HttpStatus.NOT_FOUND);
154             }
155         }
156     }
157
158     @GetMapping("/policy")
159     @ApiOperation(value = "Returns a policy configuration") //
160     @ApiResponses(
161         value = { //
162             @ApiResponse(code = 200, message = "Policy found", response = Object.class), //
163             @ApiResponse(code = 404, message = "Policy is not found")} //
164     )
165     public ResponseEntity<String> getPolicy( //
166         @ApiParam(name = "id", required = true, value = "The ID of the policy instance.")@RequestParam(name = "id", //
167             required = true) String id) {
168         try {
169             Policy p = policies.getPolicy(id);
170             return new ResponseEntity<>(p.json(), HttpStatus.OK);
171         } catch (ServiceException e) {
172             return new ResponseEntity<>(e.getMessage(), HttpStatus.NOT_FOUND);
173         }
174     }
175
176     @DeleteMapping("/policy")
177     @ApiOperation(value = "Delete a policy", response = Object.class)
178     @ApiResponses(
179         value = { //
180             @ApiResponse(code = 204, message = "Policy deleted", response = Object.class),
181             @ApiResponse(code = 404, message = "Policy is not found", response = String.class),
182             @ApiResponse(code = 423, message = "RIC is not operational", response = String.class)})
183     public Mono<ResponseEntity<Object>> deletePolicy( //
184         @ApiParam(name = "id", required = true, value = "The ID of the policy instance.")@RequestParam(name = "id", //
185             required = true) String id) {
186         try {
187             Policy policy = policies.getPolicy(id);
188             keepServiceAlive(policy.ownerServiceName());
189             Ric ric = policy.ric();
190             return ric.getLock().lock(LockType.SHARED) //
191                 .flatMap(notUsed -> assertRicStateIdle(ric)) //
192                 .flatMap(notUsed -> a1ClientFactory.createA1Client(policy.ric())) //
193                 .doOnNext(notUsed -> policies.remove(policy)) //
194                 .flatMap(client -> client.deletePolicy(policy)) //
195                 .doOnNext(notUsed -> ric.getLock().unlockBlocking()) //
196                 .doOnError(notUsed -> ric.getLock().unlockBlocking()) //
197                 .flatMap(notUsed -> Mono.just(new ResponseEntity<>(HttpStatus.NO_CONTENT)))
198                 .onErrorResume(this::handleException);
199         } catch (ServiceException e) {
200             return Mono.just(new ResponseEntity<>(HttpStatus.NOT_FOUND));
201         }
202     }
203
204     @PutMapping(path = "/policy")
205     @ApiOperation(value = "Put a policy", response = String.class)
206     @ApiResponses(
207         value = { //
208             @ApiResponse(code = 201, message = "Policy created", response = Object.class), //
209             @ApiResponse(code = 200, message = "Policy updated", response = Object.class), //
210             @ApiResponse(code = 423, message = "RIC is not operational", response = String.class), //
211             @ApiResponse(code = 404, message = "RIC or policy type is not found", response = String.class) //
212         })
213     public Mono<ResponseEntity<Object>> putPolicy( //
214         @ApiParam(name = "type", required = false, value = "The name of the policy type.") //
215             @RequestParam(name = "type", required = false, defaultValue = "") String typeName, //
216         @ApiParam(name = "id", required = true, value = "The ID of the policy instance.")@RequestParam(name = "id", //
217             required = true) String instanceId, //
218         @ApiParam(name = "ric", required = true, value = "The name of the Near-RT RIC where the policy will be " +//
219             "created.")@RequestParam(name = "ric", required = true) String ricName, //
220         @ApiParam(name = "service", required = true, value = "The name of the service creating the policy.") //
221             @RequestParam(name = "service", required = true) String service, //
222         @ApiParam(name = "transient", required = false, value = "If the policy is transient or not (boolean " +//
223             "defaulted to false). A policy is transient if it will be forgotten when the service needs to " +//
224             "reconnect to the Near-RT RIC.")@RequestParam(name = "transient", required = false, //
225             defaultValue = "false") boolean isTransient, //
226         @RequestBody Object jsonBody) {
227
228         String jsonString = gson.toJson(jsonBody);
229         Ric ric = rics.get(ricName);
230         PolicyType type = policyTypes.get(typeName);
231         keepServiceAlive(service);
232         if (ric == null || type == null) {
233             return Mono.just(new ResponseEntity<>(HttpStatus.NOT_FOUND));
234         }
235         Policy policy = ImmutablePolicy.builder() //
236             .id(instanceId) //
237             .json(jsonString) //
238             .type(type) //
239             .ric(ric) //
240             .ownerServiceName(service) //
241             .lastModified(getTimeStampUtc()) //
242             .isTransient(isTransient) //
243             .build();
244
245         final boolean isCreate = this.policies.get(policy.id()) == null;
246
247         return ric.getLock().lock(LockType.SHARED) //
248             .flatMap(notUsed -> assertRicStateIdle(ric)) //
249             .flatMap(notUsed -> checkSupportedType(ric, type)) //
250             .flatMap(notUsed -> validateModifiedPolicy(policy)) //
251             .flatMap(notUsed -> a1ClientFactory.createA1Client(ric)) //
252             .flatMap(client -> client.putPolicy(policy)) //
253             .doOnNext(notUsed -> policies.put(policy)) //
254             .doOnNext(notUsed -> ric.getLock().unlockBlocking()) //
255             .doOnError(trowable -> ric.getLock().unlockBlocking()) //
256             .flatMap(notUsed -> Mono.just(new ResponseEntity<>(isCreate ? HttpStatus.CREATED : HttpStatus.OK))) //
257             .onErrorResume(this::handleException);
258     }
259
260     @SuppressWarnings({"unchecked"})
261     private <T> Mono<ResponseEntity<T>> createResponseEntity(String message, HttpStatus status) {
262         ResponseEntity<T> re = new ResponseEntity<>((T) message, status);
263         return Mono.just(re);
264     }
265
266     private <T> Mono<ResponseEntity<T>> handleException(Throwable throwable) {
267         if (throwable instanceof WebClientResponseException) {
268             WebClientResponseException e = (WebClientResponseException) throwable;
269             return createResponseEntity(e.getResponseBodyAsString(), e.getStatusCode());
270         } else if (throwable instanceof RejectionException) {
271             RejectionException e = (RejectionException) throwable;
272             return createResponseEntity(e.getMessage(), e.getStatus());
273         } else {
274             return createResponseEntity(throwable.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
275         }
276     }
277
278     private Mono<Object> validateModifiedPolicy(Policy policy) {
279         // Check that ric is not updated
280         Policy current = this.policies.get(policy.id());
281         if (current != null && !current.ric().name().equals(policy.ric().name())) {
282             RejectionException e = new RejectionException("Policy cannot change RIC, policyId: " + current.id() + //
283                 ", RIC name: " + current.ric().name() + //
284                 ", new name: " + policy.ric().name(), HttpStatus.CONFLICT);
285             logger.debug("Request rejected, {}", e.getMessage());
286             return Mono.error(e);
287         }
288         return Mono.just("OK");
289     }
290
291     private Mono<Object> checkSupportedType(Ric ric, PolicyType type) {
292         if (!ric.isSupportingType(type.name())) {
293             logger.debug("Request rejected, type not supported, RIC: {}", ric);
294             RejectionException e = new RejectionException(
295                 "Type: " + type.name() + " not supported by RIC: " + ric.name(), HttpStatus.NOT_FOUND);
296             return Mono.error(e);
297         }
298         return Mono.just("OK");
299     }
300
301     private Mono<Object> assertRicStateIdle(Ric ric) {
302         if (ric.getState() == Ric.RicState.AVAILABLE) {
303             return Mono.just("OK");
304         } else {
305             logger.debug("Request rejected RIC not IDLE, ric: {}", ric);
306             RejectionException e = new RejectionException(
307                 "Ric is not operational, RIC name: " + ric.name() + ", state: " + ric.getState(), HttpStatus.LOCKED);
308             return Mono.error(e);
309         }
310     }
311
312     @GetMapping("/policies")
313     @ApiOperation(value = "Query policies")
314     @ApiResponses(
315         value = {
316             @ApiResponse(code = 200, message = "Policies", response = PolicyInfo.class, responseContainer = "List"),
317             @ApiResponse(code = 404, message = "RIC or type not found", response = String.class)})
318     public ResponseEntity<String> getPolicies( //
319         @ApiParam(name = "type", required = false, value = "The name of the policy type to get policies for.") //
320             @RequestParam(name = "type", required = false) String type, //
321         @ApiParam(name = "ric", required = false, value = "The name of the Near-RT RIC to get policies for.") //
322             @RequestParam(name = "ric", required = false) String ric, //
323         @ApiParam(name = "service", required = false, value = "The name of the service to get policies for.") //
324             @RequestParam(name = "service", required = false) String service) //
325     {
326         if ((type != null && this.policyTypes.get(type) == null)) {
327             return new ResponseEntity<>("Policy type not found", HttpStatus.NOT_FOUND);
328         }
329         if ((ric != null && this.rics.get(ric) == null)) {
330             return new ResponseEntity<>("RIC not found", HttpStatus.NOT_FOUND);
331         }
332
333         String filteredPolicies = policiesToJson(filter(type, ric, service));
334         return new ResponseEntity<>(filteredPolicies, HttpStatus.OK);
335     }
336
337     @GetMapping("/policy_ids")
338     @ApiOperation(value = "Query policies, only IDs returned")
339     @ApiResponses(
340         value = {@ApiResponse(code = 200, message = "Policy ids", response = String.class, responseContainer = "List"),
341             @ApiResponse(code = 404, message = "RIC or type not found", response = String.class)})
342     public ResponseEntity<String> getPolicyIds( //
343         @ApiParam(name = "type", required = false, value = "The name of the policy type to get policies for.") //
344             @RequestParam(name = "type", required = false) String type, //
345         @ApiParam(name = "ric", required = false, value = "The name of the Near-RT RIC to get policies for.") //
346             @RequestParam(name = "ric", required = false) String ric, //
347         @ApiParam(name = "service", required = false, value = "The name of the service to get policies for.") //
348             @RequestParam(name = "service", required = false) String service) //
349     {
350         if ((type != null && this.policyTypes.get(type) == null)) {
351             return new ResponseEntity<>("Policy type not found", HttpStatus.NOT_FOUND);
352         }
353         if ((ric != null && this.rics.get(ric) == null)) {
354             return new ResponseEntity<>("RIC not found", HttpStatus.NOT_FOUND);
355         }
356
357         String policyIdsJson = toPolicyIdsJson(filter(type, ric, service));
358         return new ResponseEntity<>(policyIdsJson, HttpStatus.OK);
359     }
360
361     @GetMapping("/policy_status")
362     @ApiOperation(value = "Returns a policy status") //
363     @ApiResponses(
364         value = { //
365             @ApiResponse(code = 200, message = "Policy status", response = Object.class), //
366             @ApiResponse(code = 404, message = "Policy is not found", response = String.class)} //
367     )
368     public Mono<ResponseEntity<String>> getPolicyStatus( //
369         @ApiParam(name = "id", required = true, value = "The ID of the policy.")@RequestParam(name = "id", //
370             required = true) String id) {
371         try {
372             Policy policy = policies.getPolicy(id);
373
374             return a1ClientFactory.createA1Client(policy.ric()) //
375                 .flatMap(client -> client.getPolicyStatus(policy)) //
376                 .flatMap(status -> Mono.just(new ResponseEntity<>(status, HttpStatus.OK)))
377                 .onErrorResume(this::handleException);
378         } catch (ServiceException e) {
379             return Mono.just(new ResponseEntity<>(e.getMessage(), HttpStatus.NOT_FOUND));
380         }
381     }
382
383     private void keepServiceAlive(String name) {
384         Service s = this.services.get(name);
385         if (s != null) {
386             s.keepAlive();
387         }
388     }
389
390     private boolean include(String filter, String value) {
391         return filter == null || value.equals(filter);
392     }
393
394     private Collection<Policy> filter(Collection<Policy> collection, String type, String ric, String service) {
395         if (type == null && ric == null && service == null) {
396             return collection;
397         }
398         List<Policy> filtered = new ArrayList<>();
399         for (Policy p : collection) {
400             if (include(type, p.type().name()) && include(ric, p.ric().name())
401                 && include(service, p.ownerServiceName())) {
402                 filtered.add(p);
403             }
404         }
405         return filtered;
406     }
407
408     private Collection<Policy> filter(String type, String ric, String service) {
409         if (type != null) {
410             return filter(policies.getForType(type), null, ric, service);
411         } else if (service != null) {
412             return filter(policies.getForService(service), type, ric, null);
413         } else if (ric != null) {
414             return filter(policies.getForRic(ric), type, null, service);
415         } else {
416             return policies.getAll();
417         }
418     }
419
420     private String policiesToJson(Collection<Policy> policies) {
421         List<PolicyInfo> v = new ArrayList<>(policies.size());
422         for (Policy p : policies) {
423             PolicyInfo policyInfo = new PolicyInfo();
424             policyInfo.id = p.id();
425             policyInfo.json = fromJson(p.json());
426             policyInfo.ric = p.ric().name();
427             policyInfo.type = p.type().name();
428             policyInfo.service = p.ownerServiceName();
429             policyInfo.lastModified = p.lastModified();
430             if (!policyInfo.validate()) {
431                 logger.error("BUG, all fields must be set");
432             }
433             v.add(policyInfo);
434         }
435         return gson.toJson(v);
436     }
437
438     private Object fromJson(String jsonStr) {
439         return gson.fromJson(jsonStr, Object.class);
440     }
441
442     private String toPolicyTypeSchemasJson(Collection<PolicyType> types) {
443         StringBuilder result = new StringBuilder();
444         result.append("[");
445         boolean first = true;
446         for (PolicyType t : types) {
447             if (!first) {
448                 result.append(",");
449             }
450             first = false;
451             result.append(t.schema());
452         }
453         result.append("]");
454         return result.toString();
455     }
456
457     private String toPolicyTypeIdsJson(Collection<PolicyType> types) {
458         List<String> v = new ArrayList<>(types.size());
459         for (PolicyType t : types) {
460             v.add(t.name());
461         }
462         return gson.toJson(v);
463     }
464
465     private String toPolicyIdsJson(Collection<Policy> policies) {
466         List<String> v = new ArrayList<>(policies.size());
467         for (Policy p : policies) {
468             v.add(p.id());
469         }
470         return gson.toJson(v);
471     }
472
473     private String getTimeStampUtc() {
474         return java.time.Instant.now().toString();
475     }
476
477 }