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