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