Adapting to OSC A1 API
[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(value = {@ApiResponse(code = 200, message = "Policy Types found")})
80     public ResponseEntity<String> getPolicySchemas(@RequestParam(name = "ric", required = false) String ricName) {
81         synchronized (this.policyTypes) {
82             if (ricName == null) {
83                 Collection<PolicyType> types = this.policyTypes.getAll();
84                 return new ResponseEntity<String>(toPolicyTypeSchemasJson(types), HttpStatus.OK);
85             } else {
86                 try {
87                     Collection<PolicyType> types = rics.getRic(ricName).getSupportedPolicyTypes();
88                     return new ResponseEntity<String>(toPolicyTypeSchemasJson(types), HttpStatus.OK);
89                 } catch (ServiceException e) {
90                     return new ResponseEntity<String>(e.toString(), HttpStatus.NOT_FOUND);
91                 }
92             }
93         }
94     }
95
96     @GetMapping("/policy_schema")
97     @ApiOperation(value = "Returns one policy type schema definition")
98     @ApiResponses(value = {@ApiResponse(code = 200, message = "Policy Type found")})
99     public ResponseEntity<String> getPolicySchema(@RequestParam(name = "id", required = true) String id) {
100         try {
101             PolicyType type = policyTypes.getType(id);
102             return new ResponseEntity<String>(type.schema(), HttpStatus.OK);
103         } catch (ServiceException e) {
104             return new ResponseEntity<String>(e.toString(), HttpStatus.NOT_FOUND);
105         }
106     }
107
108     @GetMapping("/policy_types")
109     @ApiOperation(value = "Returns policy types")
110     @ApiResponses(value = {@ApiResponse(code = 200, message = "Policy Types found")})
111     public ResponseEntity<String> getPolicyTypes(@RequestParam(name = "ric", required = false) String ricName) {
112         synchronized (this.policyTypes) {
113             if (ricName == null) {
114                 Collection<PolicyType> types = this.policyTypes.getAll();
115                 return new ResponseEntity<String>(toPolicyTypeIdsJson(types), HttpStatus.OK);
116             } else {
117                 try {
118                     Collection<PolicyType> types = rics.getRic(ricName).getSupportedPolicyTypes();
119                     return new ResponseEntity<String>(toPolicyTypeIdsJson(types), HttpStatus.OK);
120                 } catch (ServiceException e) {
121                     return new ResponseEntity<String>(e.toString(), HttpStatus.NOT_FOUND);
122                 }
123             }
124         }
125     }
126
127     @GetMapping("/policy")
128     @ApiOperation(value = "Returns the policy")
129     @ApiResponses(
130         value = {@ApiResponse(code = 200, message = "Policy found"),
131             @ApiResponse(code = 204, message = "Policy is not found")})
132     public ResponseEntity<String> getPolicy( //
133         @RequestParam(name = "instance", required = true) String instance) {
134         try {
135             Policy p = policies.getPolicy(instance);
136             return new ResponseEntity<String>(p.json(), HttpStatus.OK);
137         } catch (ServiceException e) {
138             return new ResponseEntity<String>(e.getMessage(), HttpStatus.NO_CONTENT);
139         }
140     }
141
142     @DeleteMapping("/policy")
143     @ApiOperation(value = "Deletes the policy")
144     @ApiResponses(value = {@ApiResponse(code = 204, message = "Policy deleted")})
145     public Mono<ResponseEntity<Void>> deletePolicy( //
146         @RequestParam(name = "instance", required = true) String id) {
147         Policy policy = policies.get(id);
148         if (policy != null && policy.ric().state().equals(Ric.RicState.IDLE)) {
149             policies.remove(policy);
150             return a1ClientFactory.createA1Client(policy.ric()) //
151                 .flatMap(client -> client.deletePolicy(policy)) //
152                 .flatMap(notUsed -> {
153                     return Mono.just(new ResponseEntity<>(HttpStatus.NO_CONTENT));
154                 });
155         } else {
156             return Mono.just(new ResponseEntity<>(HttpStatus.NOT_FOUND));
157         }
158     }
159
160     @PutMapping(path = "/policy")
161     @ApiOperation(value = "Create the policy")
162     @ApiResponses(value = {@ApiResponse(code = 201, message = "Policy created")})
163     public Mono<ResponseEntity<String>> putPolicy( //
164         @RequestParam(name = "type", required = true) String typeName, //
165         @RequestParam(name = "instance", required = true) String instanceId, //
166         @RequestParam(name = "ric", required = true) String ricName, //
167         @RequestParam(name = "service", required = true) String service, //
168         @RequestBody String jsonBody) {
169
170         Ric ric = rics.get(ricName);
171         PolicyType type = policyTypes.get(typeName);
172         if (ric != null && type != null && ric.state().equals(Ric.RicState.IDLE)) {
173             Policy policy = ImmutablePolicy.builder() //
174                 .id(instanceId) //
175                 .json(jsonBody) //
176                 .type(type) //
177                 .ric(ric) //
178                 .ownerServiceName(service) //
179                 .lastModified(getTimeStampUTC()) //
180                 .build();
181             return a1ClientFactory.createA1Client(ric) //
182                 .flatMap(client -> client.putPolicy(policy)) //
183                 .doOnNext(notUsed -> policies.put(policy)) //
184                 .flatMap(notUsed -> {
185                     return Mono.just(new ResponseEntity<>(HttpStatus.CREATED));
186                 });
187         }
188         return Mono.just(new ResponseEntity<>(HttpStatus.NOT_FOUND));
189     }
190
191     @GetMapping("/policies")
192     @ApiOperation(value = "Returns the policies")
193     @ApiResponses(value = {@ApiResponse(code = 200, message = "Policies found")})
194     public ResponseEntity<String> getPolicies( //
195         @RequestParam(name = "type", required = false) String type, //
196         @RequestParam(name = "ric", required = false) String ric, //
197         @RequestParam(name = "service", required = false) String service) //
198     {
199         synchronized (policies) {
200             Collection<Policy> result = null;
201
202             if (type != null) {
203                 result = policies.getForType(type);
204                 result = filter(result, null, ric, service);
205             } else if (service != null) {
206                 result = policies.getForService(service);
207                 result = filter(result, type, ric, null);
208             } else if (ric != null) {
209                 result = policies.getForRic(ric);
210                 result = filter(result, type, null, service);
211             } else {
212                 result = policies.getAll();
213             }
214
215             return new ResponseEntity<String>(policiesToJson(result), HttpStatus.OK);
216         }
217     }
218
219     private boolean include(String filter, String value) {
220         return filter == null || value.equals(filter);
221     }
222
223     private Collection<Policy> filter(Collection<Policy> collection, String type, String ric, String service) {
224         if (type == null && ric == null && service == null) {
225             return collection;
226         }
227         Vector<Policy> filtered = new Vector<>();
228         for (Policy p : collection) {
229             if (include(type, p.type().name()) && include(ric, p.ric().name())
230                 && include(service, p.ownerServiceName())) {
231                 filtered.add(p);
232             }
233         }
234         return filtered;
235     }
236
237     private String policiesToJson(Collection<Policy> policies) {
238         Vector<PolicyInfo> v = new Vector<>(policies.size());
239         for (Policy p : policies) {
240             PolicyInfo policyInfo = ImmutablePolicyInfo.builder() //
241                 .json(p.json()) //
242                 .id(p.id()) //
243                 .ric(p.ric().name()) //
244                 .type(p.type().name()) //
245                 .service(p.ownerServiceName()) //
246                 .lastModified(p.lastModified()) //
247                 .build();
248             v.add(policyInfo);
249         }
250         return gson.toJson(v);
251     }
252
253     private String toPolicyTypeSchemasJson(Collection<PolicyType> types) {
254         StringBuilder result = new StringBuilder();
255         result.append("[");
256         boolean first = true;
257         for (PolicyType t : types) {
258             if (!first) {
259                 result.append(",");
260             }
261             first = false;
262             result.append(t.schema());
263         }
264         result.append("]");
265         return result.toString();
266     }
267
268     private String toPolicyTypeIdsJson(Collection<PolicyType> types) {
269         Vector<String> v = new Vector<>(types.size());
270         for (PolicyType t : types) {
271             v.add(t.name());
272         }
273         return gson.toJson(v);
274     }
275
276     private String getTimeStampUTC() {
277         return java.time.Instant.now().toString();
278     }
279
280 }