aboutsummaryrefslogtreecommitdiffstats
path: root/a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/controllers/v2/PolicyController.java
blob: 23dcba71e9bab57e5bdec4f981106954595497e2 (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
/*-
 * ========================LICENSE_START=================================
 * ONAP : ccsdk oran
 * ======================================================================
 * Copyright (C) 2019-2023 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.v2;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

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 java.util.Map;

import lombok.Getter;

import org.onap.ccsdk.oran.a1policymanagementservice.clients.A1ClientFactory;
import org.onap.ccsdk.oran.a1policymanagementservice.controllers.api.v2.A1PolicyManagementApi;
import org.onap.ccsdk.oran.a1policymanagementservice.controllers.authorization.AuthorizationCheck;
import org.onap.ccsdk.oran.a1policymanagementservice.controllers.authorization.PolicyAuthorizationRequest.Input.AccessType;
import org.onap.ccsdk.oran.a1policymanagementservice.exceptions.EntityNotFoundException;
import org.onap.ccsdk.oran.a1policymanagementservice.exceptions.ServiceException;
import org.onap.ccsdk.oran.a1policymanagementservice.models.v2.PolicyTypeDefinition;
import org.onap.ccsdk.oran.a1policymanagementservice.models.v2.PolicyInfo;
import org.onap.ccsdk.oran.a1policymanagementservice.models.v2.PolicyTypeIdList;
import org.onap.ccsdk.oran.a1policymanagementservice.models.v2.PolicyInfoList;
import org.onap.ccsdk.oran.a1policymanagementservice.models.v2.PolicyIdList;
import org.onap.ccsdk.oran.a1policymanagementservice.models.v2.PolicyStatusInfo;
import org.onap.ccsdk.oran.a1policymanagementservice.repository.*;
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.RestController;
import org.springframework.web.reactive.function.client.WebClientException;
import org.springframework.web.reactive.function.client.WebClientResponseException;

import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

@RestController("PolicyControllerV2")
@Tag(//
        name = PolicyController.API_NAME, //
        description = PolicyController.API_DESCRIPTION //
)
public class PolicyController implements A1PolicyManagementApi {

    public static final String API_NAME = "A1 Policy Management";
    public static final String API_DESCRIPTION = "";

    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;
    @Autowired
    private ObjectMapper objectMapper;
    @Autowired
    private AuthorizationCheck authorization;

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

    @Override
    public Mono<ResponseEntity<Object>> getPolicyTypeDefinition(String policyTypeId, ServerWebExchange exchange)
            throws EntityNotFoundException, JsonProcessingException {
        PolicyType type = policyTypes.getType(policyTypeId);
        JsonNode node = objectMapper.readTree(type.getSchema());
        PolicyTypeDefinition policyTypeDefinition = new PolicyTypeDefinition().policySchema(node);
        return Mono.just(new ResponseEntity<>(policyTypeDefinition, HttpStatus.OK));
    }

    @Override
    public Mono<ResponseEntity<Object>> getPolicyTypes(String ricId, String typeName, String compatibleWithVersion, ServerWebExchange exchange) throws Exception {
        if (compatibleWithVersion != null && typeName == null) {
            throw new ServiceException("Parameter " + Consts.COMPATIBLE_WITH_VERSION_PARAM + " can only be used when "
                    + Consts.TYPE_NAME_PARAM + " is given", HttpStatus.BAD_REQUEST);
        }

        Collection<PolicyType> types =
                ricId != null ? rics.getRic(ricId).getSupportedPolicyTypes() : this.policyTypes.getAll();

        types = PolicyTypes.filterTypes(types, typeName, compatibleWithVersion);
        return Mono.just(new ResponseEntity<>(toPolicyTypeIdsJson(types), HttpStatus.OK));
    }


    @Override
    public Mono<ResponseEntity<Object>> getPolicy(String policyId, final ServerWebExchange exchange)
            throws EntityNotFoundException {
        Policy policy = policies.getPolicy(policyId);
        return authorization.doAccessControl(exchange.getRequest().getHeaders().toSingleValueMap(), policy, AccessType.READ) //
                .map(x -> new ResponseEntity<>((Object) toPolicyInfo(policy), HttpStatus.OK)) //
                .onErrorResume(this::handleException);
    }

    @Override
    public Mono<ResponseEntity<Object>> deletePolicy(String policyId, ServerWebExchange exchange) throws Exception {

        Policy policy = policies.getPolicy(policyId);
        keepServiceAlive(policy.getOwnerServiceId());

        return authorization.doAccessControl(exchange.getRequest().getHeaders().toSingleValueMap(), policy, AccessType.WRITE)
                .flatMap(x -> policy.getRic().getLock().lock(Lock.LockType.SHARED, "deletePolicy"))
                .flatMap(grant -> deletePolicy(grant, policy))
                .onErrorResume(this::handleException);
    }

    Mono<ResponseEntity<Object>> deletePolicy(Lock.Grant grant, Policy policy) {
        return checkRicStateIdle(policy.getRic()) //
                .flatMap(notUsed -> a1ClientFactory.createA1Client(policy.getRic()))
                .doOnNext(notUsed -> policies.remove(policy))
                .doFinally(x -> grant.unlockBlocking())
                .flatMap(client -> client.deletePolicy(policy))
                .map(notUsed -> new ResponseEntity<>(HttpStatus.NO_CONTENT))
                .onErrorResume(this::handleException);
    }

    @Override
    public Mono<ResponseEntity<Object>> putPolicy(final Mono<PolicyInfo> policyInfo, final ServerWebExchange exchange) {

        return policyInfo.flatMap(policyInfoValue -> {
                String jsonString  = gson.toJson(policyInfoValue.getPolicyData());
            return Mono.zip(
                            Mono.justOrEmpty(rics.get(policyInfoValue.getRicId()))
                                    .switchIfEmpty(Mono.error(new EntityNotFoundException("Near-RT RIC not found"))),
                            Mono.justOrEmpty(policyTypes.get(policyInfoValue.getPolicytypeId()))
                                    .switchIfEmpty(Mono.error(new EntityNotFoundException("policy type not found")))
                    )
                    .flatMap(tuple -> {
                        Ric ric = tuple.getT1();
                        PolicyType type = tuple.getT2();

                        Policy policy = Policy.builder()
                                .id(policyInfoValue.getPolicyId())
                                .json(jsonString)
                                .type(type)
                                .ric(ric)
                                .ownerServiceId(policyInfoValue.getServiceId())
                                .lastModified(Instant.now())
                                .isTransient(policyInfoValue.getTransient())
                                .statusNotificationUri(policyInfoValue.getStatusNotificationUri() == null ? "" : policyInfoValue.getStatusNotificationUri())
                                .build();

                        return authorization.doAccessControl(exchange.getRequest().getHeaders().toSingleValueMap(), policy, AccessType.WRITE)
                                .flatMap(x -> ric.getLock().lock(Lock.LockType.SHARED, "putPolicy"))
                                .flatMap(grant -> putPolicy(grant, policy));
                    })
                    .onErrorResume(this::handleException);
        });
    }



    private Mono<ResponseEntity<Object>> putPolicy(Lock.Grant grant, Policy policy) {
        final boolean isCreate = this.policies.get(policy.getId()) == null;
        final Ric ric = policy.getRic();

        return checkRicStateIdle(ric) //
                .flatMap(notUsed -> checkSupportedType(ric, policy.getType())) //
                .flatMap(notUsed -> validateModifiedPolicy(policy)) //
                .flatMap(notUsed -> a1ClientFactory.createA1Client(ric)) //
                .flatMap(client -> client.putPolicy(policy)) //
                .doOnNext(notUsed -> policies.put(policy)) //
                .doFinally(x -> grant.unlockBlocking()) //
                .flatMap(notUsed -> Mono.just(new ResponseEntity<>(isCreate ? HttpStatus.CREATED : HttpStatus.OK))) //
                .onErrorResume(this::handleException);

    }

    private Mono<ResponseEntity<Object>> handleException(Throwable throwable) {
        if (throwable instanceof WebClientResponseException) {
            WebClientResponseException e = (WebClientResponseException) throwable;
            return ErrorResponse.createMono(e.getResponseBodyAsString(), e.getStatusCode());
        } else if (throwable instanceof WebClientException) {
            WebClientException e = (WebClientException) throwable;
            return ErrorResponse.createMono(e.getMessage(), HttpStatus.BAD_GATEWAY);
        } else if (throwable instanceof RejectionException) {
            RejectionException e = (RejectionException) throwable;
            return ErrorResponse.createMono(e.getMessage(), e.getStatus());
        } else if (throwable instanceof ServiceException) {
            ServiceException e = (ServiceException) throwable;
            return ErrorResponse.createMono(e.getMessage(), e.getHttpStatus());
        } else {
            return ErrorResponse.createMono(throwable.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

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

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

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

    @Override
    public Mono<ResponseEntity<Object>> getPolicyInstances(String policyTypeId, String ricId, String serviceId, String typeName, ServerWebExchange exchange) throws Exception {
        if ((policyTypeId != null && this.policyTypes.get(policyTypeId) == null)) {
            throw new EntityNotFoundException("Policy type identity not found");
        }
        if ((ricId != null && this.rics.get(ricId) == null)) {
            throw new EntityNotFoundException("Near-RT RIC not found");
        }

        Collection<Policy> filtered = policies.filterPolicies(policyTypeId, ricId, serviceId, typeName);
        return Flux.fromIterable(filtered) //
                .flatMap(policy -> authorization.doAccessControl(exchange.getRequest().getHeaders().toSingleValueMap(), policy, AccessType.READ))
                .doOnError(e -> logger.debug("Unauthorized to read policy: {}", e.getMessage()))
                .onErrorResume(e -> Mono.empty())
                .collectList()
                .map(authPolicies -> new ResponseEntity<>((Object) policiesToJson(authPolicies), HttpStatus.OK))
                .onErrorResume(this::handleException);
    }

    @Override
    public Mono<ResponseEntity<Object>> getPolicyIds(String policyTypeId, String ricId, String serviceId, String typeName, ServerWebExchange exchange) throws Exception {
        if ((policyTypeId != null && this.policyTypes.get(policyTypeId) == null)) {
            throw new EntityNotFoundException("Policy type not found");
        }
        if ((ricId != null && this.rics.get(ricId) == null)) {
            throw new EntityNotFoundException("Near-RT RIC not found");
        }

        Collection<Policy> filtered = policies.filterPolicies(policyTypeId, ricId, serviceId, typeName);
        return Flux.fromIterable(filtered)
                .flatMap(policy -> authorization.doAccessControl(exchange.getRequest().getHeaders().toSingleValueMap(), policy, AccessType.READ))
                .doOnError(e -> logger.debug("Unauthorized to read policy: {}", e.getMessage()))
                .onErrorResume(e -> Mono.empty())
                .collectList()
                .map(authPolicies -> new ResponseEntity<>((Object)toPolicyIdsJson(authPolicies), HttpStatus.OK))
                .onErrorResume(this::handleException);
    }

    @Override
    public Mono<ResponseEntity<Object>> getPolicyStatus(String policyId, ServerWebExchange exchange) throws Exception {
        Policy policy = policies.getPolicy(policyId);

        return authorization.doAccessControl(exchange.getRequest().getHeaders().toSingleValueMap(), policy, AccessType.READ) //
                .flatMap(notUsed -> a1ClientFactory.createA1Client(policy.getRic())) //
                .flatMap(client -> client.getPolicyStatus(policy).onErrorResume(e -> Mono.just("{}"))) //
                .flatMap(status -> createPolicyStatus(policy, status))
                .onErrorResume(this::handleException);
    }

    private Mono<ResponseEntity<Object>> createPolicyStatus(Policy policy, String statusFromNearRic) {

    try {
        PolicyStatusInfo policyStatusInfo = new PolicyStatusInfo();
        policyStatusInfo.setLastModified(policy.getLastModified().toString());
        policyStatusInfo.setStatus(fromJson(statusFromNearRic));
        String policyStatusInfoAsString = objectMapper.writeValueAsString(policyStatusInfo);
        return Mono.just(new ResponseEntity<>(policyStatusInfoAsString, HttpStatus.OK));
    } catch (JsonProcessingException ex) {
        throw new RuntimeException(ex);
    }
    }

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

    private PolicyInfo toPolicyInfo(Policy policy) {
        PolicyInfo policyInfo = new PolicyInfo()
                .policyId(policy.getId())
                .policyData(gson.fromJson(policy.getJson(), Map.class))
                .ricId(policy.getRic().id())
                .policytypeId(policy.getType().getId())
                .serviceId(policy.getOwnerServiceId())
                ._transient(policy.isTransient());
        if (!policy.getStatusNotificationUri().isEmpty()) {
            policyInfo.setStatusNotificationUri(policy.getStatusNotificationUri());
        }
        return policyInfo;
    }

    private String toPolicyInfoString(Policy policy) {

        try {
            return objectMapper.writeValueAsString(toPolicyInfo(policy));
        } catch (JsonProcessingException ex) {
            throw new RuntimeException(ex);
        }
    }

    private String policiesToJson(Collection<Policy> policies) {

            try {
                List<PolicyInfo> policiesList = new ArrayList<>(policies.size());
                PolicyInfoList policyInfoList = new PolicyInfoList();
                for (Policy policy : policies) {
                    policiesList.add(toPolicyInfo(policy));
                }
                policyInfoList.setPolicies(policiesList);
                return objectMapper.writeValueAsString(policyInfoList);
            } catch(JsonProcessingException ex) {
           throw new RuntimeException(ex);
       }
    }

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

    private String toPolicyTypeIdsJson(Collection<PolicyType> policyTypes) throws JsonProcessingException {

        PolicyTypeIdList idList = new PolicyTypeIdList();
        for (PolicyType policyType : policyTypes) {
            idList.addPolicytypeIdsItem(policyType.getId());
        }

        return objectMapper.writeValueAsString(idList);
    }

    private String toPolicyIdsJson(Collection<Policy> policies) {

        try {
            List<String> policyIds = new ArrayList<>(policies.size());
            PolicyIdList idList = new PolicyIdList();
            for (Policy policy : policies) {
                policyIds.add(policy.getId());
            }
            idList.setPolicyIds(policyIds);
            return objectMapper.writeValueAsString(idList);
        } catch (JsonProcessingException ex) {
            throw new RuntimeException(ex);
        }
    }
}