aboutsummaryrefslogtreecommitdiffstats
path: root/a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/controllers/v1/PolicyController.java
blob: 1f5f7ca90d3ebb786c9822deda4bc13dc2c03a00 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
/*-
 * ========================LICENSE_START=================================
 * ONAP : ccsdk oran
 * ======================================================================
 * Copyright (C) 2019-2020 Nordix Foundation. All rights reserved.
 * ======================================================================
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * ========================LICENSE_END===================================
 */

package org.onap.ccsdk.oran.a1policymanagementservice.controllers.v1;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.media.ArraySchema;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.tags.Tag;

import java.lang.invoke.MethodHandles;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import lombok.Getter;

import org.onap.ccsdk.oran.a1policymanagementservice.clients.A1ClientFactory;
import org.onap.ccsdk.oran.a1policymanagementservice.controllers.VoidResponse;
import org.onap.ccsdk.oran.a1policymanagementservice.controllers.v2.ErrorResponse;
import org.onap.ccsdk.oran.a1policymanagementservice.exceptions.EntityNotFoundException;
import org.onap.ccsdk.oran.a1policymanagementservice.repository.ImmutablePolicy;
import org.onap.ccsdk.oran.a1policymanagementservice.repository.Lock.LockType;
import org.onap.ccsdk.oran.a1policymanagementservice.repository.Policies;
import org.onap.ccsdk.oran.a1policymanagementservice.repository.Policy;
import org.onap.ccsdk.oran.a1policymanagementservice.repository.PolicyType;
import org.onap.ccsdk.oran.a1policymanagementservice.repository.PolicyTypes;
import org.onap.ccsdk.oran.a1policymanagementservice.repository.Ric;
import org.onap.ccsdk.oran.a1policymanagementservice.repository.Rics;
import org.onap.ccsdk.oran.a1policymanagementservice.repository.Service;
import org.onap.ccsdk.oran.a1policymanagementservice.repository.Services;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.reactive.function.client.WebClientResponseException;
import reactor.core.publisher.Mono;

@RestController
@Tag(name = Consts.V1_API_NAME)
public class PolicyController {

    public static class RejectionException extends Exception {
        private static final long serialVersionUID = 1L;
        @Getter
        private final HttpStatus status;

        public RejectionException(String message, HttpStatus status) {
            super(message);
            this.status = status;
        }
    }

    @Autowired
    private Rics rics;
    @Autowired
    private PolicyTypes policyTypes;
    @Autowired
    private Policies policies;
    @Autowired
    private A1ClientFactory a1ClientFactory;
    @Autowired
    private Services services;

    private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
    private static Gson gson = new GsonBuilder().create();

    @GetMapping("/policy_schemas") //
    @Operation(summary = "Returns policy type schema definitions") //
    @ApiResponses(value = { //
            @ApiResponse(responseCode = "200", //
                    description = "Policy schemas", //
                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = Object.class)))), //
            @ApiResponse(responseCode = "404", //
                    description = "Near-RT RIC is not found", //
                    content = @Content(schema = @Schema(implementation = ErrorResponse.ErrorInfo.class))) //
    })
    public ResponseEntity<String> getPolicySchemas( //
            @Parameter(name = "ric", required = false,
                    description = "The name of the Near-RT RIC to get the definitions for.") //
            @RequestParam(name = "ric", required = false) String ricName) throws EntityNotFoundException {
        if (ricName == null) {
            Collection<PolicyType> types = this.policyTypes.getAll();
            return new ResponseEntity<>(toPolicyTypeSchemasJson(types), HttpStatus.OK);
        } else {
            Collection<PolicyType> types = rics.getRic(ricName).getSupportedPolicyTypes();
            return new ResponseEntity<>(toPolicyTypeSchemasJson(types), HttpStatus.OK);
        }
    }

    @GetMapping("/policy_schema")
    @Operation(summary = "Returns one policy type schema definition")
    @ApiResponses(value = { //
            @ApiResponse(responseCode = "200", //
                    description = "Policy schema", //
                    content = @Content(schema = @Schema(implementation = Object.class))),
            @ApiResponse(responseCode = "404", //
                    description = "The policy type is not found", //
                    content = @Content(schema = @Schema(implementation = ErrorResponse.ErrorInfo.class)))//
    })
    public ResponseEntity<String> getPolicySchema( //
            @Parameter(name = "id", required = true,
                    description = "The identity of the policy type to get the definition for.") //
            @RequestParam(name = "id", required = true) String id) throws EntityNotFoundException {
        PolicyType type = policyTypes.getType(id);
        return new ResponseEntity<>(type.schema(), HttpStatus.OK);
    }

    @GetMapping("/policy_types")
    @Operation(summary = "Query policy type names")
    @ApiResponses(value = { //
            @ApiResponse(responseCode = "200", //
                    description = "Policy type names", //
                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = String.class)))), //
            @ApiResponse(responseCode = "404", //
                    description = "Near-RT RIC is not found", //
                    content = @Content(schema = @Schema(implementation = ErrorResponse.ErrorInfo.class)))//
    })
    public ResponseEntity<String> getPolicyTypes( //
            @Parameter(name = "ric", required = false, description = "The name of the Near-RT RIC to get types for.") //
            @RequestParam(name = "ric", required = false) String ricName) throws EntityNotFoundException {
        if (ricName == null) {
            Collection<PolicyType> types = this.policyTypes.getAll();
            return new ResponseEntity<>(toPolicyTypeIdsJson(types), HttpStatus.OK);
        } else {
            Collection<PolicyType> types = rics.getRic(ricName).getSupportedPolicyTypes();
            return new ResponseEntity<>(toPolicyTypeIdsJson(types), HttpStatus.OK);
        }
    }

    @GetMapping("/policy")
    @Operation(summary = "Returns a policy configuration") //
    @ApiResponses(value = { //
            @ApiResponse(responseCode = "200", //
                    description = "Policy found", //
                    content = @Content(schema = @Schema(implementation = Object.class))), //
            @ApiResponse(responseCode = "404", //
                    description = "Policy is not found", //
                    content = @Content(schema = @Schema(implementation = ErrorResponse.ErrorInfo.class))//
            )} //
    )
    public ResponseEntity<String> getPolicy( //
            @Parameter(name = "id", required = true, description = "The identity of the policy instance.") //
            @RequestParam(name = "id", required = true) String id) throws EntityNotFoundException {
        Policy p = policies.getPolicy(id);
        return new ResponseEntity<>(p.json(), HttpStatus.OK);
    }

    @DeleteMapping("/policy")
    @Operation(summary = "Delete a policy")
    @ApiResponses(value = { //
            @ApiResponse(responseCode = "200", //
                    description = "Not used", //
                    content = @Content(schema = @Schema(implementation = VoidResponse.class))),
            @ApiResponse(responseCode = "204", //
                    description = "Policy deleted", //
                    content = @Content(schema = @Schema(implementation = VoidResponse.class))),
            @ApiResponse(responseCode = "404", //
                    description = "Policy is not found", //
                    content = @Content(schema = @Schema(implementation = String.class))),
            @ApiResponse(responseCode = "423", //
                    description = "Near-RT RIC is not operational", //
                    content = @Content(schema = @Schema(implementation = String.class)))})
    public Mono<ResponseEntity<Object>> deletePolicy( //
            @Parameter(name = "id", required = true, description = "The identity of the policy instance.") //
            @RequestParam(name = "id", required = true) String id) throws EntityNotFoundException {
        Policy policy = policies.getPolicy(id);
        keepServiceAlive(policy.ownerServiceId());
        Ric ric = policy.ric();
        return ric.getLock().lock(LockType.SHARED) //
                .flatMap(notUsed -> assertRicStateIdle(ric)) //
                .flatMap(notUsed -> a1ClientFactory.createA1Client(policy.ric())) //
                .doOnNext(notUsed -> policies.remove(policy)) //
                .flatMap(client -> client.deletePolicy(policy)) //
                .doOnNext(notUsed -> ric.getLock().unlockBlocking()) //
                .doOnError(notUsed -> ric.getLock().unlockBlocking()) //
                .flatMap(notUsed -> Mono.just(new ResponseEntity<>(HttpStatus.NO_CONTENT)))
                .onErrorResume(this::handleException);
    }

    @PutMapping(path = "/policy")
    @Operation(summary = "Put a policy")
    @ApiResponses(value = { //
            @ApiResponse(responseCode = "201", //
                    description = "Policy created", //
                    content = @Content(schema = @Schema(implementation = VoidResponse.class))), //
            @ApiResponse(responseCode = "200", //
                    description = "Policy updated", //
                    content = @Content(schema = @Schema(implementation = VoidResponse.class))), //
            @ApiResponse(responseCode = "423", //
                    description = "Near-RT RIC is not operational", //
                    content = @Content(schema = @Schema(implementation = String.class))), //
            @ApiResponse(responseCode = "404", //
                    description = "Near-RT RIC or policy type is not found", //
                    content = @Content(schema = @Schema(implementation = String.class))) //
    })
    public Mono<ResponseEntity<Object>> putPolicy( //
            @Parameter(name = "type", required = false, description = "The name of the policy type.") //
            @RequestParam(name = "type", required = false, defaultValue = "") String typeName, //
            @Parameter(name = "id", required = true, description = "The identity of the policy instance.") //
            @RequestParam(name = "id", required = true) String instanceId, //
            @Parameter(name = "ric", required = true,
                    description = "The name of the Near-RT RIC where the policy will be " + //
                            "created.") //
            @RequestParam(name = "ric", required = true) String ricName, //
            @Parameter(name = "service", required = true, description = "The name of the service creating the policy.") //
            @RequestParam(name = "service", required = true) String service, //
            @Parameter(name = "transient", required = false,
                    description = "If the policy is transient or not (boolean " + //
                            "defaulted to false). A policy is transient if it will be forgotten when the service needs to "
                            + //
                            "reconnect to the Near-RT RIC.") //
            @RequestParam(name = "transient", required = false, defaultValue = "false") boolean isTransient, //
            @RequestBody Object jsonBody) {

        String jsonString = gson.toJson(jsonBody);
        Ric ric = rics.get(ricName);
        PolicyType type = policyTypes.get(typeName);
        keepServiceAlive(service);
        if (ric == null || type == null) {
            return Mono.just(new ResponseEntity<>(HttpStatus.NOT_FOUND));
        }
        Policy policy = ImmutablePolicy.builder() //
                .id(instanceId) //
                .json(jsonString) //
                .type(type) //
                .ric(ric) //
                .ownerServiceId(service) //
                .lastModified(Instant.now()) //
                .isTransient(isTransient) //
                .statusNotificationUri("") //
                .build();

        final boolean isCreate = this.policies.get(policy.id()) == null;

        return ric.getLock().lock(LockType.SHARED) //
                .flatMap(notUsed -> assertRicStateIdle(ric)) //
                .flatMap(notUsed -> checkSupportedType(ric, type)) //
                .flatMap(notUsed -> validateModifiedPolicy(policy)) //
                .flatMap(notUsed -> a1ClientFactory.createA1Client(ric)) //
                .flatMap(client -> client.putPolicy(policy)) //
                .doOnNext(notUsed -> policies.put(policy)) //
                .doOnNext(notUsed -> ric.getLock().unlockBlocking()) //
                .doOnError(trowable -> ric.getLock().unlockBlocking()) //
                .flatMap(notUsed -> Mono.just(new ResponseEntity<>(isCreate ? HttpStatus.CREATED : HttpStatus.OK))) //
                .onErrorResume(this::handleException);
    }

    @SuppressWarnings({"unchecked"})
    private <T> Mono<ResponseEntity<T>> createResponseEntity(String message, HttpStatus status) {
        ResponseEntity<T> re = new ResponseEntity<>((T) message, status);
        return Mono.just(re);
    }

    private <T> Mono<ResponseEntity<T>> handleException(Throwable throwable) {
        if (throwable instanceof WebClientResponseException) {
            WebClientResponseException e = (WebClientResponseException) throwable;
            return createResponseEntity(e.getResponseBodyAsString(), e.getStatusCode());
        } else if (throwable instanceof RejectionException) {
            RejectionException e = (RejectionException) throwable;
            return createResponseEntity(e.getMessage(), e.getStatus());
        } else {
            return createResponseEntity(throwable.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    private Mono<Object> validateModifiedPolicy(Policy policy) {
        // Check that ric is not updated
        Policy current = this.policies.get(policy.id());
        if (current != null && !current.ric().id().equals(policy.ric().id())) {
            RejectionException e = new RejectionException("Policy cannot change RIC, policyId: " + current.id() + //
                    ", RIC name: " + current.ric().id() + //
                    ", new name: " + policy.ric().id(), HttpStatus.CONFLICT);
            logger.debug("Request rejected, {}", e.getMessage());
            return Mono.error(e);
        }
        return Mono.just("OK");
    }

    private Mono<Object> checkSupportedType(Ric ric, PolicyType type) {
        if (!ric.isSupportingType(type.id())) {
            logger.debug("Request rejected, type not supported, RIC: {}", ric);
            RejectionException e = new RejectionException("Type: " + type.id() + " not supported by RIC: " + ric.id(),
                    HttpStatus.NOT_FOUND);
            return Mono.error(e);
        }
        return Mono.just("OK");
    }

    private Mono<Object> assertRicStateIdle(Ric ric) {
        if (ric.getState() == Ric.RicState.AVAILABLE) {
            return Mono.just("OK");
        } else {
            logger.debug("Request rejected RIC not IDLE, ric: {}", ric);
            RejectionException e = new RejectionException(
                    "Ric is not operational, RIC name: " + ric.id() + ", state: " + ric.getState(), HttpStatus.LOCKED);
            return Mono.error(e);
        }
    }

    @GetMapping("/policies")
    @Operation(summary = "Query policies")
    @ApiResponses(value = { //
            @ApiResponse(responseCode = "200", //
                    description = "Policies", //
                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = PolicyInfo.class)))), //
            @ApiResponse(responseCode = "404", //
                    description = "Near-RT RIC or type not found", //
                    content = @Content(schema = @Schema(implementation = String.class)))})
    public ResponseEntity<String> getPolicies( //
            @Parameter(name = "type", required = false,
                    description = "The name of the policy type to get policies for.") //
            @RequestParam(name = "type", required = false) String type, //
            @Parameter(name = "ric", required = false, description = "The name of the Near-RT RIC to get policies for.") //
            @RequestParam(name = "ric", required = false) String ric, //
            @Parameter(name = "service", required = false, description = "The name of the service to get policies for.") //
            @RequestParam(name = "service", required = false) String service) //
    {
        if ((type != null && this.policyTypes.get(type) == null)) {
            return new ResponseEntity<>("Policy type not found", HttpStatus.NOT_FOUND);
        }
        if ((ric != null && this.rics.get(ric) == null)) {
            return new ResponseEntity<>("Near-RT RIC not found", HttpStatus.NOT_FOUND);
        }

        String filteredPolicies = policiesToJson(filter(type, ric, service));
        return new ResponseEntity<>(filteredPolicies, HttpStatus.OK);
    }

    @GetMapping("/policy_ids")
    @Operation(summary = "Query policies, only policy identities returned")
    @ApiResponses(value = { //
            @ApiResponse(responseCode = "200", //
                    description = "Policy identitiess", //
                    content = @Content(array = @ArraySchema(schema = @Schema(implementation = String.class)))),
            @ApiResponse(responseCode = "404", //
                    description = "Near-RT RIC or type not found", //
                    content = @Content(schema = @Schema(implementation = String.class)))})
    public ResponseEntity<String> getPolicyIds( //
            @Parameter(name = "type", required = false,
                    description = "The name of the policy type to get policies for.") //
            @RequestParam(name = "type", required = false) String type, //
            @Parameter(name = "ric", required = false, description = "The name of the Near-RT RIC to get policies for.") //
            @RequestParam(name = "ric", required = false) String ric, //
            @Parameter(name = "service", required = false, description = "The name of the service to get policies for.") //
            @RequestParam(name = "service", required = false) String service) //
    {
        if ((type != null && this.policyTypes.get(type) == null)) {
            return new ResponseEntity<>("Policy type not found", HttpStatus.NOT_FOUND);
        }
        if ((ric != null && this.rics.get(ric) == null)) {
            return new ResponseEntity<>("Near-RT RIC not found", HttpStatus.NOT_FOUND);
        }

        String policyIdsJson = toPolicyIdsJson(filter(type, ric, service));
        return new ResponseEntity<>(policyIdsJson, HttpStatus.OK);
    }

    @GetMapping("/policy_status")
    @Operation(summary = "Returns a policy status") //
    @ApiResponses(value = { //
            @ApiResponse(responseCode = "200", //
                    description = "Policy status", //
                    content = @Content(schema = @Schema(implementation = Object.class))), //
            @ApiResponse(responseCode = "404", //
                    description = "Policy is not found", //
                    content = @Content(schema = @Schema(implementation = String.class))) //
    })
    public Mono<ResponseEntity<String>> getPolicyStatus( //
            @Parameter(name = "id", required = true, description = "The identity of the policy.") @RequestParam(
                    name = "id", //
                    required = true) String id)
            throws EntityNotFoundException {
        Policy policy = policies.getPolicy(id);

        return a1ClientFactory.createA1Client(policy.ric()) //
                .flatMap(client -> client.getPolicyStatus(policy)) //
                .flatMap(status -> Mono.just(new ResponseEntity<>(status, HttpStatus.OK)))
                .onErrorResume(this::handleException);
    }

    private void keepServiceAlive(String name) {
        Service s = this.services.get(name);
        if (s != null) {
            s.keepAlive();
        }
    }

    private boolean include(String filter, String value) {
        return filter == null || value.equals(filter);
    }

    private Collection<Policy> filter(Collection<Policy> collection, String type, String ric, String service) {
        if (type == null && ric == null && service == null) {
            return collection;
        }
        List<Policy> filtered = new ArrayList<>();
        for (Policy p : collection) {
            if (include(type, p.type().id()) && include(ric, p.ric().id()) && include(service, p.ownerServiceId())) {
                filtered.add(p);
            }
        }
        return filtered;
    }

    private Collection<Policy> filter(String type, String ric, String service) {
        if (type != null) {
            return filter(policies.getForType(type), null, ric, service);
        } else if (service != null) {
            return filter(policies.getForService(service), type, ric, null);
        } else if (ric != null) {
            return filter(policies.getForRic(ric), type, null, service);
        } else {
            return policies.getAll();
        }
    }

    private String policiesToJson(Collection<Policy> policies) {
        List<PolicyInfo> v = new ArrayList<>(policies.size());
        for (Policy p : policies) {
            PolicyInfo policyInfo = new PolicyInfo();
            policyInfo.id = p.id();
            policyInfo.json = fromJson(p.json());
            policyInfo.ric = p.ric().id();
            policyInfo.type = p.type().id();
            policyInfo.service = p.ownerServiceId();
            policyInfo.lastModified = p.lastModified().toString();
            if (!policyInfo.validate()) {
                logger.error("BUG, all fields must be set");
            }
            v.add(policyInfo);
        }
        return gson.toJson(v);
    }

    private Object fromJson(String jsonStr) {
        return gson.fromJson(jsonStr, Object.class);
    }

    private String toPolicyTypeSchemasJson(Collection<PolicyType> types) {
        StringBuilder result = new StringBuilder();
        result.append("[");
        boolean first = true;
        for (PolicyType t : types) {
            if (!first) {
                result.append(",");
            }
            first = false;
            result.append(t.schema());
        }
        result.append("]");
        return result.toString();
    }

    private String toPolicyTypeIdsJson(Collection<PolicyType> types) {
        List<String> v = new ArrayList<>(types.size());
        for (PolicyType t : types) {
            v.add(t.id());
        }
        return gson.toJson(v);
    }

    private String toPolicyIdsJson(Collection<Policy> policies) {
        List<String> v = new ArrayList<>(policies.size());
        for (Policy p : policies) {
            v.add(p.id());
        }
        return gson.toJson(v);
    }

}