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