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