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