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