c18ec81b1cbaa10c2e619e14c0df34ccb7e3eb93
[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.v2;
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.MediaType;
58 import org.springframework.http.ResponseEntity;
59 import org.springframework.web.bind.annotation.DeleteMapping;
60 import org.springframework.web.bind.annotation.GetMapping;
61 import org.springframework.web.bind.annotation.PathVariable;
62 import org.springframework.web.bind.annotation.PutMapping;
63 import org.springframework.web.bind.annotation.RequestBody;
64 import org.springframework.web.bind.annotation.RequestParam;
65 import org.springframework.web.bind.annotation.RestController;
66 import org.springframework.web.reactive.function.client.WebClientResponseException;
67 import reactor.core.publisher.Mono;
68
69 @RestController("PolicyControllerV2")
70 @Api(tags = {Consts.V2_API_NAME})
71 public class PolicyController {
72
73     public static class RejectionException extends Exception {
74         private static final long serialVersionUID = 1L;
75
76         @Getter
77         private final HttpStatus status;
78
79         public RejectionException(String message, HttpStatus status) {
80             super(message);
81             this.status = status;
82         }
83     }
84
85     @Autowired
86     private Rics rics;
87     @Autowired
88     private PolicyTypes policyTypes;
89     @Autowired
90     private Policies policies;
91     @Autowired
92     private A1ClientFactory a1ClientFactory;
93     @Autowired
94     private Services services;
95
96     private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
97     private static Gson gson = new GsonBuilder() //
98             .create(); //
99
100     @GetMapping(path = Consts.V2_API_ROOT + "/policy-types/{policyTypeId}", produces = MediaType.APPLICATION_JSON_VALUE)
101     @ApiOperation(value = "Returns a policy type definition")
102     @ApiResponses(value = { //
103             @ApiResponse(code = 200, message = "Policy type", response = PolicyTypeInfo.class), //
104             @ApiResponse(code = 404, message = "Near-RT RIC is not found", response = ErrorResponse.ErrorInfo.class)})
105     public ResponseEntity<Object> getPolicyType( //
106             @PathVariable("policyTypeId") String policyTypeId) {
107         try {
108             PolicyType type = policyTypes.getType(policyTypeId);
109             PolicyTypeInfo info = new PolicyTypeInfo(type.schema());
110             return new ResponseEntity<>(gson.toJson(info), HttpStatus.OK);
111         } catch (ServiceException e) {
112             return ErrorResponse.create(e, HttpStatus.NOT_FOUND);
113         }
114     }
115
116     @GetMapping(path = Consts.V2_API_ROOT + "/policy-types", produces = MediaType.APPLICATION_JSON_VALUE)
117     @ApiOperation(value = "Query policy type identities", produces = MediaType.APPLICATION_JSON_VALUE)
118     @ApiResponses(value = {@ApiResponse(code = 200, message = "Policy type IDs", response = PolicyTypeIdList.class),
119             @ApiResponse(code = 404, message = "Near-RT RIC is not found", response = ErrorResponse.ErrorInfo.class)})
120     public ResponseEntity<Object> getPolicyTypes( //
121             @ApiParam(name = Consts.RIC_ID_PARAM, required = false,
122                     value = "The identity of the Near-RT RIC to get types for.") //
123             @RequestParam(name = Consts.RIC_ID_PARAM, required = false) String ricId) {
124         if (ricId == null) {
125             Collection<PolicyType> types = this.policyTypes.getAll();
126             return new ResponseEntity<>(toPolicyTypeIdsJson(types), HttpStatus.OK);
127         } else {
128             try {
129                 Collection<PolicyType> types = rics.getRic(ricId).getSupportedPolicyTypes();
130                 return new ResponseEntity<>(toPolicyTypeIdsJson(types), HttpStatus.OK);
131             } catch (ServiceException e) {
132                 return ErrorResponse.create(e, HttpStatus.NOT_FOUND);
133             }
134         }
135     }
136
137     @GetMapping(path = Consts.V2_API_ROOT + "/policies/{policy_id}", produces = MediaType.APPLICATION_JSON_VALUE)
138     @ApiOperation(value = "Returns a policy") //
139     @ApiResponses(value = { //
140             @ApiResponse(code = 200, message = "Policy found", response = PolicyInfo.class), //
141             @ApiResponse(code = 404, message = "Policy is not found", response = ErrorResponse.ErrorInfo.class)} //
142     )
143     public ResponseEntity<Object> getPolicy( //
144             @PathVariable(name = Consts.POLICY_ID_PARAM, required = true) String id) {
145         try {
146             Policy p = policies.getPolicy(id);
147             return new ResponseEntity<>(gson.toJson(toPolicyInfo(p)), HttpStatus.OK);
148         } catch (ServiceException e) {
149             return ErrorResponse.create(e, HttpStatus.NOT_FOUND);
150         }
151     }
152
153     @DeleteMapping(Consts.V2_API_ROOT + "/policies/{policy_id}")
154     @ApiOperation(value = "Delete a policy")
155     @ApiResponses(value = { //
156             @ApiResponse(code = 200, message = "Not used", response = VoidResponse.class),
157             @ApiResponse(code = 204, message = "Policy deleted", response = VoidResponse.class),
158             @ApiResponse(code = 404, message = "Policy is not found", response = ErrorResponse.ErrorInfo.class),
159             @ApiResponse(code = 423, message = "Near-RT RIC is not operational",
160                     response = ErrorResponse.ErrorInfo.class)})
161     public Mono<ResponseEntity<Object>> deletePolicy( //
162             @PathVariable(Consts.POLICY_ID_PARAM) String policyId) {
163         try {
164             Policy policy = policies.getPolicy(policyId);
165             keepServiceAlive(policy.ownerServiceId());
166             Ric ric = policy.ric();
167             return ric.getLock().lock(LockType.SHARED) //
168                     .flatMap(notUsed -> assertRicStateIdle(ric)) //
169                     .flatMap(notUsed -> a1ClientFactory.createA1Client(policy.ric())) //
170                     .doOnNext(notUsed -> policies.remove(policy)) //
171                     .flatMap(client -> client.deletePolicy(policy)) //
172                     .doOnNext(notUsed -> ric.getLock().unlockBlocking()) //
173                     .doOnError(notUsed -> ric.getLock().unlockBlocking()) //
174                     .flatMap(notUsed -> Mono.just(new ResponseEntity<>(HttpStatus.NO_CONTENT)))
175                     .onErrorResume(this::handleException);
176         } catch (ServiceException e) {
177             return ErrorResponse.createMono(e, HttpStatus.NOT_FOUND);
178         }
179     }
180
181     @PutMapping(path = Consts.V2_API_ROOT + "/policies", produces = MediaType.APPLICATION_JSON_VALUE)
182     @ApiOperation(value = "Create or update a policy")
183     @ApiResponses(value = { //
184             @ApiResponse(code = 201, message = "Policy created", response = VoidResponse.class), //
185             @ApiResponse(code = 200, message = "Policy updated", response = VoidResponse.class), //
186             @ApiResponse(code = 423, message = "Near-RT RIC is not operational",
187                     response = ErrorResponse.ErrorInfo.class), //
188             @ApiResponse(code = 404, message = "Near-RT RIC or policy type is not found",
189                     response = ErrorResponse.ErrorInfo.class) //
190     })
191     public Mono<ResponseEntity<Object>> putPolicy(@RequestBody PolicyInfo policyInfo) {
192
193         String jsonString = gson.toJson(policyInfo.policyData);
194         Ric ric = rics.get(policyInfo.ricId);
195         PolicyType type = policyTypes.get(policyInfo.policyTypeId);
196         keepServiceAlive(policyInfo.serviceId);
197         if (ric == null || type == null) {
198             return ErrorResponse.createMono("Near-RT RIC or policy type not found", HttpStatus.NOT_FOUND);
199         }
200         Policy policy = ImmutablePolicy.builder() //
201                 .id(policyInfo.policyId) //
202                 .json(jsonString) //
203                 .type(type) //
204                 .ric(ric) //
205                 .ownerServiceId(policyInfo.serviceId) //
206                 .lastModified(Instant.now()) //
207                 .isTransient(policyInfo.isTransient) //
208                 .statusNotificationUri(policyInfo.statusNotificationUri == null ? "" : policyInfo.statusNotificationUri) //
209                 .build();
210
211         final boolean isCreate = this.policies.get(policy.id()) == null;
212
213         return ric.getLock().lock(LockType.SHARED) //
214                 .flatMap(notUsed -> assertRicStateIdle(ric)) //
215                 .flatMap(notUsed -> checkSupportedType(ric, type)) //
216                 .flatMap(notUsed -> validateModifiedPolicy(policy)) //
217                 .flatMap(notUsed -> a1ClientFactory.createA1Client(ric)) //
218                 .flatMap(client -> client.putPolicy(policy)) //
219                 .doOnNext(notUsed -> policies.put(policy)) //
220                 .doOnNext(notUsed -> ric.getLock().unlockBlocking()) //
221                 .doOnError(trowable -> ric.getLock().unlockBlocking()) //
222                 .flatMap(notUsed -> Mono.just(new ResponseEntity<>(isCreate ? HttpStatus.CREATED : HttpStatus.OK))) //
223                 .onErrorResume(this::handleException);
224     }
225
226     private Mono<ResponseEntity<Object>> handleException(Throwable throwable) {
227         if (throwable instanceof WebClientResponseException) {
228             WebClientResponseException e = (WebClientResponseException) throwable;
229             return ErrorResponse.createMono(e.getResponseBodyAsString(), e.getStatusCode());
230         } else if (throwable instanceof RejectionException) {
231             RejectionException e = (RejectionException) throwable;
232             return ErrorResponse.createMono(e.getMessage(), e.getStatus());
233         } else {
234             return ErrorResponse.createMono(throwable.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
235         }
236     }
237
238     private Mono<Object> validateModifiedPolicy(Policy policy) {
239         // Check that ric is not updated
240         Policy current = this.policies.get(policy.id());
241         if (current != null && !current.ric().id().equals(policy.ric().id())) {
242             RejectionException e = new RejectionException("Policy cannot change RIC, policyId: " + current.id() + //
243                     ", RIC ID: " + current.ric().id() + //
244                     ", new ID: " + policy.ric().id(), HttpStatus.CONFLICT);
245             logger.debug("Request rejected, {}", e.getMessage());
246             return Mono.error(e);
247         }
248         return Mono.just("{}");
249     }
250
251     private Mono<Object> checkSupportedType(Ric ric, PolicyType type) {
252         if (!ric.isSupportingType(type.id())) {
253             logger.debug("Request rejected, type not supported, RIC: {}", ric);
254             RejectionException e = new RejectionException("Type: " + type.id() + " not supported by RIC: " + ric.id(),
255                     HttpStatus.NOT_FOUND);
256             return Mono.error(e);
257         }
258         return Mono.just("{}");
259     }
260
261     private void assertRicStateIdleSync(Ric ric) throws ServiceException {
262         if (ric.getState() != Ric.RicState.AVAILABLE) {
263             throw new ServiceException("Near-RT RIC: " + ric.id() + " is " + ric.getState());
264         }
265     }
266
267     private Mono<Object> assertRicStateIdle(Ric ric) {
268         if (ric.getState() == Ric.RicState.AVAILABLE) {
269             return Mono.just("{}");
270         } else {
271             logger.debug("Request rejected Near-RT RIC not IDLE, ric: {}", ric);
272             RejectionException e = new RejectionException(
273                     "Near-RT RIC: is not operational, id: " + ric.id() + ", state: " + ric.getState(),
274                     HttpStatus.LOCKED);
275             return Mono.error(e);
276         }
277     }
278
279     static final String GET_POLICIES_QUERY_DETAILS =
280             "Returns a list of A1 policies matching given search criteria. <br>" //
281                     + "If several query parameters are defined, the policies matching all conditions are returned.";
282
283     @GetMapping(path = Consts.V2_API_ROOT + "/policy_instances", produces = MediaType.APPLICATION_JSON_VALUE)
284     @ApiOperation(value = "Query for A1 policy instances", notes = GET_POLICIES_QUERY_DETAILS)
285     @ApiResponses(value = { //
286             @ApiResponse(code = 200, message = "Policies", response = PolicyInfoList.class),
287             @ApiResponse(code = 404, message = "Near-RT RIC, policy type or service not found",
288                     response = ErrorResponse.ErrorInfo.class)})
289     public ResponseEntity<Object> getPolicies( //
290             @ApiParam(name = Consts.POLICY_TYPE_ID_PARAM, required = false,
291                     value = "The identity of the policy type to get policies for.") //
292             @RequestParam(name = Consts.POLICY_TYPE_ID_PARAM, required = false) String type, //
293             @ApiParam(name = Consts.RIC_ID_PARAM, required = false,
294                     value = "The identity of the Near-RT RIC to get policies for.") //
295             @RequestParam(name = Consts.RIC_ID_PARAM, required = false) String ric, //
296             @ApiParam(name = Consts.SERVICE_ID_PARAM, required = false,
297                     value = "The identity of the service to get policies for.") //
298             @RequestParam(name = Consts.SERVICE_ID_PARAM, required = false) String service) //
299     {
300         if ((type != null && this.policyTypes.get(type) == null)) {
301             return ErrorResponse.create("Policy type not found", HttpStatus.NOT_FOUND);
302         }
303         if ((ric != null && this.rics.get(ric) == null)) {
304             return ErrorResponse.create("Near-RT RIC not found", HttpStatus.NOT_FOUND);
305         }
306
307         String filteredPolicies = policiesToJson(filter(type, ric, service));
308         return new ResponseEntity<>(filteredPolicies, HttpStatus.OK);
309     }
310
311     @GetMapping(path = Consts.V2_API_ROOT + "/policies", produces = MediaType.APPLICATION_JSON_VALUE)
312     @ApiOperation(value = "Query policy identities", notes = GET_POLICIES_QUERY_DETAILS)
313     @ApiResponses(value = { //
314             @ApiResponse(code = 200, message = "Policy identities", response = PolicyIdList.class), @ApiResponse(
315                     code = 404, message = "Near-RT RIC or type not found", response = ErrorResponse.ErrorInfo.class)})
316     public ResponseEntity<Object> getPolicyIds( //
317             @ApiParam(name = Consts.POLICY_TYPE_ID_PARAM, required = false,
318                     value = "The identity of the policy type to get policies for.") //
319             @RequestParam(name = Consts.POLICY_TYPE_ID_PARAM, required = false) String policyTypeId, //
320             @ApiParam(name = Consts.RIC_ID_PARAM, required = false,
321                     value = "The identity of the Near-RT RIC to get policies for.") //
322             @RequestParam(name = Consts.RIC_ID_PARAM, required = false) String ricId, //
323             @ApiParam(name = Consts.SERVICE_ID_PARAM, required = false,
324                     value = "The identity of the service to get policies for.") //
325             @RequestParam(name = Consts.SERVICE_ID_PARAM, required = false) String serviceId) //
326     {
327         if ((policyTypeId != null && this.policyTypes.get(policyTypeId) == null)) {
328             return ErrorResponse.create("Policy type not found", HttpStatus.NOT_FOUND);
329         }
330         if ((ricId != null && this.rics.get(ricId) == null)) {
331             return ErrorResponse.create("Near-RT RIC not found", HttpStatus.NOT_FOUND);
332         }
333
334         String policyIdsJson = toPolicyIdsJson(filter(policyTypeId, ricId, serviceId));
335         return new ResponseEntity<>(policyIdsJson, HttpStatus.OK);
336     }
337
338     @GetMapping(path = Consts.V2_API_ROOT + "/policies/{policy_id}/status", produces = MediaType.APPLICATION_JSON_VALUE)
339     @ApiOperation(value = "Returns a policy status") //
340     @ApiResponses(value = { //
341             @ApiResponse(code = 200, message = "Policy status", response = PolicyStatusInfo.class), //
342             @ApiResponse(code = 404, message = "Policy is not found", response = ErrorResponse.ErrorInfo.class)} //
343     )
344     public Mono<ResponseEntity<Object>> getPolicyStatus( //
345             @PathVariable(Consts.POLICY_ID_PARAM) String policyId) {
346         try {
347             Policy policy = policies.getPolicy(policyId);
348
349             return a1ClientFactory.createA1Client(policy.ric()) //
350                     .flatMap(client -> client.getPolicyStatus(policy).onErrorResume(e -> Mono.just("{}"))) //
351                     .flatMap(status -> createPolicyStatus(policy, status)) //
352                     .onErrorResume(this::handleException);
353         } catch (ServiceException e) {
354             return ErrorResponse.createMono(e, HttpStatus.NOT_FOUND);
355         }
356     }
357
358     private Mono<ResponseEntity<Object>> createPolicyStatus(Policy policy, String statusFromNearRic) {
359         PolicyStatusInfo info = new PolicyStatusInfo(policy.lastModified(), fromJson(statusFromNearRic));
360         String str = gson.toJson(info);
361         return Mono.just(new ResponseEntity<>((Object) str, HttpStatus.OK));
362     }
363
364     private void keepServiceAlive(String name) {
365         Service s = this.services.get(name);
366         if (s != null) {
367             s.keepAlive();
368         }
369     }
370
371     private boolean include(String filter, String value) {
372         return filter == null || value.equals(filter);
373     }
374
375     private Collection<Policy> filter(Collection<Policy> collection, String type, String ric, String service) {
376         if (type == null && ric == null && service == null) {
377             return collection;
378         }
379         List<Policy> filtered = new ArrayList<>();
380         for (Policy p : collection) {
381             if (include(type, p.type().id()) && include(ric, p.ric().id()) && include(service, p.ownerServiceId())) {
382                 filtered.add(p);
383             }
384         }
385         return filtered;
386     }
387
388     private Collection<Policy> filter(String type, String ric, String service) {
389         if (type != null) {
390             return filter(policies.getForType(type), null, ric, service);
391         } else if (service != null) {
392             return filter(policies.getForService(service), type, ric, null);
393         } else if (ric != null) {
394             return filter(policies.getForRic(ric), type, null, service);
395         } else {
396             return policies.getAll();
397         }
398     }
399
400     private PolicyInfo toPolicyInfo(Policy p) {
401         PolicyInfo policyInfo = new PolicyInfo();
402         policyInfo.policyId = p.id();
403         policyInfo.policyData = fromJson(p.json());
404         policyInfo.ricId = p.ric().id();
405         policyInfo.policyTypeId = p.type().id();
406         policyInfo.serviceId = p.ownerServiceId();
407         if (!p.statusNotificationUri().isEmpty()) {
408             policyInfo.statusNotificationUri = p.statusNotificationUri();
409         }
410         if (!policyInfo.validate()) {
411             logger.error("BUG, all mandatory fields must be set");
412         }
413
414         return policyInfo;
415     }
416
417     private String policiesToJson(Collection<Policy> policies) {
418         List<PolicyInfo> v = new ArrayList<>(policies.size());
419         for (Policy p : policies) {
420             v.add(toPolicyInfo(p));
421         }
422         PolicyInfoList list = new PolicyInfoList(v);
423         return gson.toJson(list);
424     }
425
426     private Object fromJson(String jsonStr) {
427         return gson.fromJson(jsonStr, Object.class);
428     }
429
430     private String toPolicyTypeIdsJson(Collection<PolicyType> types) {
431         List<String> v = new ArrayList<>(types.size());
432         for (PolicyType t : types) {
433             v.add(t.id());
434         }
435         PolicyTypeIdList ids = new PolicyTypeIdList(v);
436         return gson.toJson(ids);
437     }
438
439     private String toPolicyIdsJson(Collection<Policy> policies) {
440         List<String> v = new ArrayList<>(policies.size());
441         for (Policy p : policies) {
442             v.add(p.id());
443         }
444         return gson.toJson(new PolicyIdList(v));
445     }
446
447 }