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