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