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