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