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