3a49ff127ea9eb6c9af115c89d2a90cf113809d0
[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 org.oransc.policyagent.clients.A1ClientFactory;
36 import org.oransc.policyagent.configuration.ApplicationConfig;
37 import org.oransc.policyagent.exceptions.ServiceException;
38 import org.oransc.policyagent.repository.ImmutablePolicy;
39 import org.oransc.policyagent.repository.Lock.LockType;
40 import org.oransc.policyagent.repository.Policies;
41 import org.oransc.policyagent.repository.Policy;
42 import org.oransc.policyagent.repository.PolicyType;
43 import org.oransc.policyagent.repository.PolicyTypes;
44 import org.oransc.policyagent.repository.Ric;
45 import org.oransc.policyagent.repository.Rics;
46 import org.springframework.beans.factory.annotation.Autowired;
47 import org.springframework.http.HttpStatus;
48 import org.springframework.http.ResponseEntity;
49 import org.springframework.web.bind.annotation.DeleteMapping;
50 import org.springframework.web.bind.annotation.GetMapping;
51 import org.springframework.web.bind.annotation.PutMapping;
52 import org.springframework.web.bind.annotation.RequestBody;
53 import org.springframework.web.bind.annotation.RequestParam;
54 import org.springframework.web.bind.annotation.RestController;
55 import reactor.core.publisher.Mono;
56
57 @RestController
58 @Api(value = "Policy Management API")
59 public class PolicyController {
60
61     private final Rics rics;
62     private final PolicyTypes policyTypes;
63     private final Policies policies;
64     private final A1ClientFactory a1ClientFactory;
65
66     private static Gson gson = new GsonBuilder() //
67         .serializeNulls() //
68         .create(); //
69
70     @Autowired
71     PolicyController(ApplicationConfig config, PolicyTypes types, Policies policies, Rics rics,
72         A1ClientFactory a1ClientFactory) {
73         this.policyTypes = types;
74         this.policies = policies;
75         this.rics = rics;
76         this.a1ClientFactory = a1ClientFactory;
77     }
78
79     @GetMapping("/policy_schemas")
80     @ApiOperation(value = "Returns policy type schema definitions")
81     @ApiResponses(
82         value = {
83             @ApiResponse(code = 200, message = "Policy schemas", response = Object.class, responseContainer = "List")})
84     public ResponseEntity<String> getPolicySchemas(@RequestParam(name = "ric", required = false) String ricName) {
85         synchronized (this.policyTypes) {
86             if (ricName == null) {
87                 Collection<PolicyType> types = this.policyTypes.getAll();
88                 return new ResponseEntity<>(toPolicyTypeSchemasJson(types), HttpStatus.OK);
89             } else {
90                 try {
91                     Collection<PolicyType> types = rics.getRic(ricName).getSupportedPolicyTypes();
92                     return new ResponseEntity<>(toPolicyTypeSchemasJson(types), HttpStatus.OK);
93                 } catch (ServiceException e) {
94                     return new ResponseEntity<>(e.toString(), HttpStatus.NOT_FOUND);
95                 }
96             }
97         }
98     }
99
100     @GetMapping("/policy_schema")
101     @ApiOperation(value = "Returns one policy type schema definition")
102     @ApiResponses(value = {@ApiResponse(code = 200, message = "Policy schema", response = Object.class)})
103     public ResponseEntity<String> getPolicySchema(@RequestParam(name = "id", required = true) String id) {
104         try {
105             PolicyType type = policyTypes.getType(id);
106             return new ResponseEntity<>(type.schema(), HttpStatus.OK);
107         } catch (ServiceException e) {
108             return new ResponseEntity<>(e.toString(), HttpStatus.NOT_FOUND);
109         }
110     }
111
112     @GetMapping("/policy_types")
113     @ApiOperation(value = "Query policy type names")
114     @ApiResponses(
115         value = {@ApiResponse(
116             code = 200,
117             message = "Policy type names",
118             response = String.class,
119             responseContainer = "List")})
120     public ResponseEntity<String> getPolicyTypes(@RequestParam(name = "ric", required = false) String ricName) {
121         synchronized (this.policyTypes) {
122             if (ricName == null) {
123                 Collection<PolicyType> types = this.policyTypes.getAll();
124                 return new ResponseEntity<>(toPolicyTypeIdsJson(types), HttpStatus.OK);
125             } else {
126                 try {
127                     Collection<PolicyType> types = rics.getRic(ricName).getSupportedPolicyTypes();
128                     return new ResponseEntity<>(toPolicyTypeIdsJson(types), HttpStatus.OK);
129                 } catch (ServiceException e) {
130                     return new ResponseEntity<>(e.toString(), HttpStatus.NOT_FOUND);
131                 }
132             }
133         }
134     }
135
136     @GetMapping("/policy")
137     @ApiOperation(value = "Returns a policy configuration") //
138     @ApiResponses(
139         value = { //
140             @ApiResponse(code = 200, message = "Policy found", response = Object.class), //
141             @ApiResponse(code = 204, message = "Policy is not found")} //
142     )
143     public ResponseEntity<String> getPolicy( //
144         @RequestParam(name = "instance", required = true) String instance) {
145         try {
146             Policy p = policies.getPolicy(instance);
147             return new ResponseEntity<>(p.json(), HttpStatus.OK);
148         } catch (ServiceException e) {
149             return new ResponseEntity<>(e.getMessage(), HttpStatus.NO_CONTENT);
150         }
151     }
152
153     @DeleteMapping("/policy")
154     @ApiOperation(value = "Delete a policy", response = Object.class)
155     @ApiResponses(value = {@ApiResponse(code = 204, message = "Policy deleted", response = Object.class)})
156     public Mono<ResponseEntity<Object>> deletePolicy( //
157         @RequestParam(name = "instance", required = true) String id) {
158         Policy policy = policies.get(id);
159         if (policy != null && policy.ric().getState() == Ric.RicState.IDLE) {
160             Ric ric = policy.ric();
161             return ric.getLock().lock(LockType.SHARED) // //
162                 .flatMap(lock -> a1ClientFactory.createA1Client(policy.ric())) //
163                 .doOnNext(notUsed -> policies.remove(policy)) //
164                 .flatMap(client -> client.deletePolicy(policy)) //
165                 .doOnNext(notUsed -> ric.getLock().unlockBlocking()) //
166                 .doOnError(notUsed -> ric.getLock().unlockBlocking()) //
167                 .flatMap(notUsed -> Mono.just(new ResponseEntity<>(HttpStatus.NO_CONTENT)));
168         } else if (policy != null) {
169             return Mono.just(new ResponseEntity<>("Busy, recovering", HttpStatus.LOCKED));
170         } else {
171             return Mono.just(new ResponseEntity<>(HttpStatus.NOT_FOUND));
172         }
173     }
174
175     @PutMapping(path = "/policy")
176     @ApiOperation(value = "Put a policy", response = String.class)
177     @ApiResponses(value = {@ApiResponse(code = 200, message = "Policy created or updated")})
178     public Mono<ResponseEntity<Object>> putPolicy( //
179         @RequestParam(name = "type", required = true) String typeName, //
180         @RequestParam(name = "instance", required = true) String instanceId, //
181         @RequestParam(name = "ric", required = true) String ricName, //
182         @RequestParam(name = "service", required = true) String service, //
183         @RequestBody Object jsonBody) {
184
185         String jsonString = gson.toJson(jsonBody);
186
187         Ric ric = rics.get(ricName);
188         PolicyType type = policyTypes.get(typeName);
189         if (ric != null && type != null && ric.getState() == Ric.RicState.IDLE) {
190             Policy policy = ImmutablePolicy.builder() //
191                 .id(instanceId) //
192                 .json(jsonString) //
193                 .type(type) //
194                 .ric(ric) //
195                 .ownerServiceName(service) //
196                 .lastModified(getTimeStampUtc()) //
197                 .build();
198
199             final boolean isCreate = this.policies.get(policy.id()) == null;
200
201             return ric.getLock().lock(LockType.SHARED) //
202                 .flatMap(p -> validateModifiedPolicy(policy)) //
203                 .flatMap(notUsed -> a1ClientFactory.createA1Client(ric)) //
204                 .flatMap(client -> client.putPolicy(policy)) //
205                 .doOnNext(notUsed -> policies.put(policy)) //
206                 .doOnNext(notUsed -> ric.getLock().unlockBlocking()) //
207                 .doOnError(t -> ric.getLock().unlockBlocking()) //
208                 .flatMap(notUsed -> Mono.just(new ResponseEntity<>(isCreate ? HttpStatus.CREATED : HttpStatus.OK))) //
209                 .onErrorResume(t -> Mono.just(new ResponseEntity<>(t.getMessage(), HttpStatus.METHOD_NOT_ALLOWED)));
210         }
211
212         return ric == null && type == null ? Mono.just(new ResponseEntity<>(HttpStatus.NOT_FOUND))
213             : Mono.just(new ResponseEntity<>(HttpStatus.CONFLICT)); // Recovering
214     }
215
216     private Mono<Object> validateModifiedPolicy(Policy policy) {
217         // Check that ric is not updated
218         Policy current = this.policies.get(policy.id());
219         if (current != null && !current.ric().name().equals(policy.ric().name())) {
220             return Mono.error(new Exception("Policy cannot change RIC, policyId: " + current.id() + //
221                 ", RIC name: " + current.ric().name() + //
222                 ", new name: " + policy.ric().name()));
223         }
224         return Mono.just("OK");
225     }
226
227     @GetMapping("/policies")
228     @ApiOperation(value = "Query policies")
229     @ApiResponses(
230         value = {
231             @ApiResponse(code = 200, message = "Policies", response = PolicyInfo.class, responseContainer = "List")})
232     public ResponseEntity<String> getPolicies( //
233         @RequestParam(name = "type", required = false) String type, //
234         @RequestParam(name = "ric", required = false) String ric, //
235         @RequestParam(name = "service", required = false) String service) //
236     {
237         synchronized (policies) {
238             Collection<Policy> result = null;
239
240             if (type != null) {
241                 result = policies.getForType(type);
242                 result = filter(result, null, ric, service);
243             } else if (service != null) {
244                 result = policies.getForService(service);
245                 result = filter(result, type, ric, null);
246             } else if (ric != null) {
247                 result = filter(policies.getForRic(ric), type, null, service);
248             } else {
249                 result = policies.getAll();
250             }
251
252             String policiesJson;
253             try {
254                 policiesJson = policiesToJson(result);
255             } catch (ServiceException e) {
256                 return new ResponseEntity<>(e.getMessage(), HttpStatus.NO_CONTENT);
257             }
258             return new ResponseEntity<>(policiesJson, HttpStatus.OK);
259         }
260     }
261
262     @GetMapping("/policy_status")
263     @ApiOperation(value = "Returns a policy status") //
264     @ApiResponses(
265         value = { //
266             @ApiResponse(code = 200, message = "Policy status", response = Object.class), //
267             @ApiResponse(code = 204, message = "Policy is not found", response = String.class)} //
268     )
269     public Mono<ResponseEntity<String>> getPolicyStatus( //
270         @RequestParam(name = "instance", required = true) String instance) {
271         try {
272             Policy policy = policies.getPolicy(instance);
273
274             return a1ClientFactory.createA1Client(policy.ric()) //
275                 .flatMap(client -> client.getPolicyStatus(policy)) //
276                 .flatMap(status -> Mono.just(new ResponseEntity<>(status, HttpStatus.OK)));
277         } catch (ServiceException e) {
278             return Mono.just(new ResponseEntity<>(e.getMessage(), HttpStatus.NO_CONTENT));
279         }
280     }
281
282     private boolean include(String filter, String value) {
283         return filter == null || value.equals(filter);
284     }
285
286     private Collection<Policy> filter(Collection<Policy> collection, String type, String ric, String service) {
287         if (type == null && ric == null && service == null) {
288             return collection;
289         }
290         List<Policy> filtered = new ArrayList<>();
291         for (Policy p : collection) {
292             if (include(type, p.type().name()) && include(ric, p.ric().name())
293                 && include(service, p.ownerServiceName())) {
294                 filtered.add(p);
295             }
296         }
297         return filtered;
298     }
299
300     private String policiesToJson(Collection<Policy> policies) throws ServiceException {
301         List<PolicyInfo> v = new ArrayList<>(policies.size());
302         for (Policy p : policies) {
303             PolicyInfo policyInfo = new PolicyInfo();
304             policyInfo.id = p.id();
305             policyInfo.json = fromJson(p.json());
306             policyInfo.ric = p.ric().name();
307             policyInfo.type = p.type().name();
308             policyInfo.service = p.ownerServiceName();
309             policyInfo.lastModified = p.lastModified();
310             if (!policyInfo.validate()) {
311                 throw new ServiceException("BUG, all fields must be set");
312             }
313             v.add(policyInfo);
314         }
315         return gson.toJson(v);
316     }
317
318     private Object fromJson(String jsonStr) {
319         return gson.fromJson(jsonStr, Object.class);
320     }
321
322     private String toPolicyTypeSchemasJson(Collection<PolicyType> types) {
323         StringBuilder result = new StringBuilder();
324         result.append("[");
325         boolean first = true;
326         for (PolicyType t : types) {
327             if (!first) {
328                 result.append(",");
329             }
330             first = false;
331             result.append(t.schema());
332         }
333         result.append("]");
334         return result.toString();
335     }
336
337     private String toPolicyTypeIdsJson(Collection<PolicyType> types) {
338         List<String> v = new ArrayList<>(types.size());
339         for (PolicyType t : types) {
340             v.add(t.name());
341         }
342         return gson.toJson(v);
343     }
344
345     private String getTimeStampUtc() {
346         return java.time.Instant.now().toString();
347     }
348
349 }