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