Added check in PUT policy
[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(notUsed -> assertRicStateIdle(ric)) //
230             .flatMap(notUsed -> checkSupportedType(ric, type)) //
231             .flatMap(notUsed -> validateModifiedPolicy(policy)) //
232             .flatMap(notUsed -> a1ClientFactory.createA1Client(ric)) //
233             .flatMap(client -> client.putPolicy(policy)) //
234             .doOnNext(notUsed -> policies.put(policy)) //
235             .doOnNext(notUsed -> ric.getLock().unlockBlocking()) //
236             .doOnError(trowable -> ric.getLock().unlockBlocking()) //
237             .flatMap(notUsed -> Mono.just(new ResponseEntity<>(isCreate ? HttpStatus.CREATED : HttpStatus.OK))) //
238             .onErrorResume(this::handleException);
239     }
240
241     @SuppressWarnings({"unchecked"})
242     private <T> Mono<ResponseEntity<T>> createResponseEntity(String message, HttpStatus status) {
243         ResponseEntity<T> re = new ResponseEntity<>((T) message, status);
244         return Mono.just(re);
245     }
246
247     private <T> Mono<ResponseEntity<T>> handleException(Throwable throwable) {
248         if (throwable instanceof WebClientResponseException) {
249             WebClientResponseException e = (WebClientResponseException) throwable;
250             return createResponseEntity(e.getResponseBodyAsString(), e.getStatusCode());
251         } else if (throwable instanceof RejectionException) {
252             RejectionException e = (RejectionException) throwable;
253             return createResponseEntity(e.getMessage(), e.getStatus());
254         } else {
255             return createResponseEntity(throwable.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
256         }
257     }
258
259     private Mono<Object> validateModifiedPolicy(Policy policy) {
260         // Check that ric is not updated
261         Policy current = this.policies.get(policy.id());
262         if (current != null && !current.ric().name().equals(policy.ric().name())) {
263             RejectionException e = new RejectionException("Policy cannot change RIC, policyId: " + current.id() + //
264                 ", RIC name: " + current.ric().name() + //
265                 ", new name: " + policy.ric().name(), HttpStatus.CONFLICT);
266             return Mono.error(e);
267         }
268         return Mono.just("OK");
269     }
270
271     private Mono<Object> checkSupportedType(Ric ric, PolicyType type) {
272         if (!ric.isSupportingType(type.name())) {
273             RejectionException e = new RejectionException(
274                 "Type: " + type.name() + " not supported by RIC: " + ric.name(), HttpStatus.NOT_FOUND);
275             return Mono.error(e);
276         }
277         return Mono.just("OK");
278     }
279
280     private Mono<Object> assertRicStateIdle(Ric ric) {
281         if (ric.getState() == Ric.RicState.AVAILABLE) {
282             return Mono.just("OK");
283         } else {
284             RejectionException e = new RejectionException(
285                 "Ric is not operational, RIC name: " + ric.name() + ", state: " + ric.getState(), HttpStatus.LOCKED);
286             return Mono.error(e);
287         }
288     }
289
290     @GetMapping("/policies")
291     @ApiOperation(value = "Query policies")
292     @ApiResponses(
293         value = {
294             @ApiResponse(code = 200, message = "Policies", response = PolicyInfo.class, responseContainer = "List"),
295             @ApiResponse(code = 404, message = "RIC or type not found", response = String.class)})
296     public ResponseEntity<String> getPolicies( //
297         @RequestParam(name = "type", required = false) String type, //
298         @RequestParam(name = "ric", required = false) String ric, //
299         @RequestParam(name = "service", required = false) String service) //
300     {
301         if ((type != null && this.policyTypes.get(type) == null)) {
302             return new ResponseEntity<>("Policy type not found", HttpStatus.NOT_FOUND);
303         }
304         if ((ric != null && this.rics.get(ric) == null)) {
305             return new ResponseEntity<>("RIC not found", HttpStatus.NOT_FOUND);
306         }
307
308         String filteredPolicies = policiesToJson(filter(type, ric, service));
309         return new ResponseEntity<>(filteredPolicies, HttpStatus.OK);
310     }
311
312     @GetMapping("/policy_ids")
313     @ApiOperation(value = "Query policies, only IDs returned")
314     @ApiResponses(
315         value = {@ApiResponse(code = 200, message = "Policy ids", response = String.class, responseContainer = "List"),
316             @ApiResponse(code = 404, message = "RIC or type not found", response = String.class)})
317     public ResponseEntity<String> getPolicyIds( //
318         @RequestParam(name = "type", required = false) String type, //
319         @RequestParam(name = "ric", required = false) String ric, //
320         @RequestParam(name = "service", required = false) String service) //
321     {
322         if ((type != null && this.policyTypes.get(type) == null)) {
323             return new ResponseEntity<>("Policy type not found", HttpStatus.NOT_FOUND);
324         }
325         if ((ric != null && this.rics.get(ric) == null)) {
326             return new ResponseEntity<>("RIC not found", HttpStatus.NOT_FOUND);
327         }
328
329         String policyIdsJson = toPolicyIdsJson(filter(type, ric, service));
330         return new ResponseEntity<>(policyIdsJson, HttpStatus.OK);
331     }
332
333     @GetMapping("/policy_status")
334     @ApiOperation(value = "Returns a policy status") //
335     @ApiResponses(
336         value = { //
337             @ApiResponse(code = 200, message = "Policy status", response = Object.class), //
338             @ApiResponse(code = 404, message = "Policy is not found", response = String.class)} //
339     )
340     public Mono<ResponseEntity<String>> getPolicyStatus( //
341         @RequestParam(name = "id", required = true) String id) {
342         try {
343             Policy policy = policies.getPolicy(id);
344
345             return a1ClientFactory.createA1Client(policy.ric()) //
346                 .flatMap(client -> client.getPolicyStatus(policy)) //
347                 .flatMap(status -> Mono.just(new ResponseEntity<>(status, HttpStatus.OK)))
348                 .onErrorResume(this::handleException);
349         } catch (ServiceException e) {
350             return Mono.just(new ResponseEntity<>(e.getMessage(), HttpStatus.NOT_FOUND));
351         }
352     }
353
354     private void keepServiceAlive(String name) {
355         Service s = this.services.get(name);
356         if (s != null) {
357             s.keepAlive();
358         }
359     }
360
361     private boolean include(String filter, String value) {
362         return filter == null || value.equals(filter);
363     }
364
365     private Collection<Policy> filter(Collection<Policy> collection, String type, String ric, String service) {
366         if (type == null && ric == null && service == null) {
367             return collection;
368         }
369         List<Policy> filtered = new ArrayList<>();
370         for (Policy p : collection) {
371             if (include(type, p.type().name()) && include(ric, p.ric().name())
372                 && include(service, p.ownerServiceName())) {
373                 filtered.add(p);
374             }
375         }
376         return filtered;
377     }
378
379     private Collection<Policy> filter(String type, String ric, String service) {
380         if (type != null) {
381             return filter(policies.getForType(type), null, ric, service);
382         } else if (service != null) {
383             return filter(policies.getForService(service), type, ric, null);
384         } else if (ric != null) {
385             return filter(policies.getForRic(ric), type, null, service);
386         } else {
387             return policies.getAll();
388         }
389     }
390
391     private String policiesToJson(Collection<Policy> policies) {
392         List<PolicyInfo> v = new ArrayList<>(policies.size());
393         for (Policy p : policies) {
394             PolicyInfo policyInfo = new PolicyInfo();
395             policyInfo.id = p.id();
396             policyInfo.json = fromJson(p.json());
397             policyInfo.ric = p.ric().name();
398             policyInfo.type = p.type().name();
399             policyInfo.service = p.ownerServiceName();
400             policyInfo.lastModified = p.lastModified();
401             if (!policyInfo.validate()) {
402                 throw new NullPointerException("BUG, all fields must be set");
403             }
404             v.add(policyInfo);
405         }
406         return gson.toJson(v);
407     }
408
409     private Object fromJson(String jsonStr) {
410         return gson.fromJson(jsonStr, Object.class);
411     }
412
413     private String toPolicyTypeSchemasJson(Collection<PolicyType> types) {
414         StringBuilder result = new StringBuilder();
415         result.append("[");
416         boolean first = true;
417         for (PolicyType t : types) {
418             if (!first) {
419                 result.append(",");
420             }
421             first = false;
422             result.append(t.schema());
423         }
424         result.append("]");
425         return result.toString();
426     }
427
428     private String toPolicyTypeIdsJson(Collection<PolicyType> types) {
429         List<String> v = new ArrayList<>(types.size());
430         for (PolicyType t : types) {
431             v.add(t.name());
432         }
433         return gson.toJson(v);
434     }
435
436     private String toPolicyIdsJson(Collection<Policy> policies) {
437         List<String> v = new ArrayList<>(policies.size());
438         for (Policy p : policies) {
439             v.add(p.id());
440         }
441         return gson.toJson(v);
442     }
443
444     private String getTimeStampUtc() {
445         return java.time.Instant.now().toString();
446     }
447
448 }