Handling of A1 STD 1.1
[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, recovering", 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)); // Recovering
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             Collection<Policy> result = null;
297
298             if (type != null) {
299                 result = policies.getForType(type);
300                 result = filter(result, null, ric, service);
301             } else if (service != null) {
302                 result = policies.getForService(service);
303                 result = filter(result, type, ric, null);
304             } else if (ric != null) {
305                 result = filter(policies.getForRic(ric), type, null, service);
306             } else {
307                 result = policies.getAll();
308             }
309
310             String policiesJson;
311             try {
312                 policiesJson = policiesToJson(result);
313             } catch (ServiceException e) {
314                 return new ResponseEntity<>(e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
315             }
316             return new ResponseEntity<>(policiesJson, HttpStatus.OK);
317         }
318     }
319
320     @GetMapping("/policy_status")
321     @ApiOperation(value = "Returns a policy status") //
322     @ApiResponses(
323         value = { //
324             @ApiResponse(code = 200, message = "Policy status", response = Object.class), //
325             @ApiResponse(code = 404, message = "Policy is not found", response = String.class)} //
326     )
327     public Mono<ResponseEntity<String>> getPolicyStatus( //
328         @RequestParam(name = "instance", required = true) String instance) {
329         try {
330             Policy policy = policies.getPolicy(instance);
331
332             return a1ClientFactory.createA1Client(policy.ric()) //
333                 .flatMap(client -> client.getPolicyStatus(policy)) //
334                 .flatMap(status -> Mono.just(new ResponseEntity<>(status, HttpStatus.OK)))
335                 .onErrorResume(this::handleException);
336         } catch (ServiceException e) {
337             return Mono.just(new ResponseEntity<>(e.getMessage(), HttpStatus.NOT_FOUND));
338         }
339     }
340
341     private void keepServiceAlive(String name) {
342         Service s = this.services.get(name);
343         if (s != null) {
344             s.keepAlive();
345         }
346     }
347
348     private boolean include(String filter, String value) {
349         return filter == null || value.equals(filter);
350     }
351
352     private Collection<Policy> filter(Collection<Policy> collection, String type, String ric, String service) {
353         if (type == null && ric == null && service == null) {
354             return collection;
355         }
356         List<Policy> filtered = new ArrayList<>();
357         for (Policy p : collection) {
358             if (include(type, p.type().name()) && include(ric, p.ric().name())
359                 && include(service, p.ownerServiceName())) {
360                 filtered.add(p);
361             }
362         }
363         return filtered;
364     }
365
366     private String policiesToJson(Collection<Policy> policies) throws ServiceException {
367         List<PolicyInfo> v = new ArrayList<>(policies.size());
368         for (Policy p : policies) {
369             PolicyInfo policyInfo = new PolicyInfo();
370             policyInfo.id = p.id();
371             policyInfo.json = fromJson(p.json());
372             policyInfo.ric = p.ric().name();
373             policyInfo.type = p.type().name();
374             policyInfo.service = p.ownerServiceName();
375             policyInfo.lastModified = p.lastModified();
376             if (!policyInfo.validate()) {
377                 throw new ServiceException("BUG, all fields must be set");
378             }
379             v.add(policyInfo);
380         }
381         return gson.toJson(v);
382     }
383
384     private Object fromJson(String jsonStr) {
385         return gson.fromJson(jsonStr, Object.class);
386     }
387
388     private String toPolicyTypeSchemasJson(Collection<PolicyType> types) {
389         StringBuilder result = new StringBuilder();
390         result.append("[");
391         boolean first = true;
392         for (PolicyType t : types) {
393             if (!first) {
394                 result.append(",");
395             }
396             first = false;
397             result.append(t.schema());
398         }
399         result.append("]");
400         return result.toString();
401     }
402
403     private String toPolicyTypeIdsJson(Collection<PolicyType> types) {
404         List<String> v = new ArrayList<>(types.size());
405         for (PolicyType t : types) {
406             v.add(t.name());
407         }
408         return gson.toJson(v);
409     }
410
411     private String getTimeStampUtc() {
412         return java.time.Instant.now().toString();
413     }
414
415 }