2d282f33540f5e1cb035a055118f9f781c8b01d4
[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.tasks;
22
23 import static org.onap.ccsdk.oran.a1policymanagementservice.repository.Ric.RicState;
24
25 import org.onap.ccsdk.oran.a1policymanagementservice.clients.A1Client;
26 import org.onap.ccsdk.oran.a1policymanagementservice.clients.A1ClientFactory;
27 import org.onap.ccsdk.oran.a1policymanagementservice.clients.AsyncRestClientFactory;
28 import org.onap.ccsdk.oran.a1policymanagementservice.controllers.ServiceCallbacks;
29 import org.onap.ccsdk.oran.a1policymanagementservice.repository.Lock.LockType;
30 import org.onap.ccsdk.oran.a1policymanagementservice.repository.Policies;
31 import org.onap.ccsdk.oran.a1policymanagementservice.repository.Policy;
32 import org.onap.ccsdk.oran.a1policymanagementservice.repository.PolicyType;
33 import org.onap.ccsdk.oran.a1policymanagementservice.repository.PolicyTypes;
34 import org.onap.ccsdk.oran.a1policymanagementservice.repository.Ric;
35 import org.onap.ccsdk.oran.a1policymanagementservice.repository.Rics;
36 import org.onap.ccsdk.oran.a1policymanagementservice.repository.Services;
37 import org.slf4j.Logger;
38 import org.slf4j.LoggerFactory;
39 import org.springframework.web.reactive.function.client.WebClientResponseException;
40
41 import reactor.core.publisher.Flux;
42 import reactor.core.publisher.Mono;
43
44 /**
45  * Synchronizes the content of a Near-RT RIC with the content in the repository.
46  * This means:
47  * <p>
48  * load all policy types
49  * <p>
50  * send all policy instances to the Near-RT RIC
51  * <p>
52  * if that fails remove all policy instances
53  * <p>
54  * Notify subscribing services
55  */
56 @SuppressWarnings("squid:S2629") // Invoke method(s) only conditionally
57 public class RicSynchronizationTask {
58
59     private static final Logger logger = LoggerFactory.getLogger(RicSynchronizationTask.class);
60     static final int CONCURRENCY_RIC = 1; // How many paralell requests that is sent to one NearRT RIC
61
62     private final A1ClientFactory a1ClientFactory;
63     private final PolicyTypes policyTypes;
64     private final Policies policies;
65     private final Services services;
66     private final Rics rics;
67     private final AsyncRestClientFactory restClientFactory;
68
69     public RicSynchronizationTask(A1ClientFactory a1ClientFactory, PolicyTypes policyTypes, Policies policies,
70             Services services, AsyncRestClientFactory restClientFactory, Rics rics) {
71         this.a1ClientFactory = a1ClientFactory;
72         this.policyTypes = policyTypes;
73         this.policies = policies;
74         this.services = services;
75         this.restClientFactory = restClientFactory;
76         this.rics = rics;
77     }
78
79     public void run(Ric ric) {
80         logger.debug("Ric synchronization task created: {}", ric.getConfig().getRicId());
81
82         if (ric.getState() == RicState.SYNCHRONIZING) {
83             logger.debug("Ric: {} is already being synchronized", ric.getConfig().getRicId());
84             return;
85         }
86
87         ric.getLock().lock(LockType.EXCLUSIVE, "RicSynchronizationTask") //
88                 .flatMap(notUsed -> synchronizeRic(ric)) //
89                 .doFinally(sig -> ric.getLock().unlockBlocking()) //
90                 .subscribe();
91     }
92
93     public Mono<Ric> synchronizeRic(Ric ric) {
94         return this.a1ClientFactory.createA1Client(ric) //
95                 .doOnNext(client -> ric.setState(RicState.SYNCHRONIZING)) //
96                 .flatMapMany(client -> runSynchronization(ric, client)) //
97                 .doOnError(t -> { //
98                     logger.warn("Synchronization failure for ric: {}, reason: {}", ric.id(), t.getMessage()); //
99                     ric.setState(RicState.UNAVAILABLE); //
100                     deletePoliciesIfNotRecreatable(t, ric);
101                 }) //
102                 .collectList() //
103                 .flatMap(notUsed -> onSynchronizationComplete(ric)) //
104                 .onErrorResume(t -> Mono.just(ric));
105     }
106
107     /**
108      * If a 4xx error is received, allpolicies are deleted. This is just to avoid
109      * cyclical receovery due to that the NearRT RIC cannot accept a previously
110      * policy.
111      */
112     private void deletePoliciesIfNotRecreatable(Throwable throwable, Ric ric) {
113         if (throwable instanceof WebClientResponseException) {
114             WebClientResponseException responseException = (WebClientResponseException) throwable;
115             if (responseException.getStatusCode().is4xxClientError()) {
116                 deleteAllPoliciesInRepository(ric);
117             }
118         }
119     }
120
121     private void deleteAllPoliciesInRepository(Ric ric) {
122         for (Policy policy : policies.getForRic(ric.id())) {
123             this.policies.remove(policy);
124         }
125     }
126
127     public Flux<PolicyType> synchronizePolicyTypes(Ric ric, A1Client a1Client) {
128         return a1Client.getPolicyTypeIdentities() //
129                 .doOnNext(x -> ric.clearSupportedPolicyTypes()) //
130                 .flatMapMany(Flux::fromIterable) //
131                 .doOnNext(typeId -> logger.debug("For ric: {}, handling type: {}", ric.getConfig().getRicId(), typeId)) //
132                 .flatMap(policyTypeId -> getPolicyType(policyTypeId, a1Client), CONCURRENCY_RIC) //
133                 .doOnNext(ric::addSupportedPolicyType); //
134     }
135
136     private Flux<Object> runSynchronization(Ric ric, A1Client a1Client) {
137         Flux<PolicyType> synchronizedTypes = synchronizePolicyTypes(ric, a1Client);
138         Flux<?> policiesDeletedInRic = a1Client.deleteAllPolicies();
139         Flux<Policy> policiesRecreatedInRic = recreateAllPoliciesInRic(ric, a1Client);
140
141         return Flux.concat(synchronizedTypes, policiesDeletedInRic, policiesRecreatedInRic);
142     }
143
144     private Mono<Ric> onSynchronizationComplete(Ric ric) {
145         if (this.rics.get(ric.id()) == null) {
146             logger.debug("Policies removed in removed ric: {}", ric.id());
147             return Mono.empty();
148         }
149         logger.debug("Synchronization completed for: {}", ric.id());
150         ric.setState(RicState.AVAILABLE);
151         ServiceCallbacks callbacks = new ServiceCallbacks(this.restClientFactory);
152         return callbacks.notifyServicesRicAvailable(ric, services) //
153                 .collectList() //
154                 .map(list -> ric);
155     }
156
157     private Mono<PolicyType> getPolicyType(String policyTypeId, A1Client a1Client) {
158         if (policyTypes.contains(policyTypeId)) {
159             return Mono.just(policyTypes.get(policyTypeId));
160         }
161         return a1Client.getPolicyTypeSchema(policyTypeId) //
162                 .map(schema -> createPolicyType(policyTypeId, schema));
163     }
164
165     private PolicyType createPolicyType(String policyTypeId, String schema) {
166         PolicyType pt = PolicyType.builder().id(policyTypeId).schema(schema).build();
167         policyTypes.put(pt);
168         return pt;
169     }
170
171     private Flux<Policy> putPolicy(Policy policy, Ric ric, A1Client a1Client) {
172         logger.trace("Recreating policy: {}, for ric: {}", policy.getId(), ric.getConfig().getRicId());
173         return a1Client.putPolicy(policy) //
174                 .flatMapMany(notUsed -> Flux.just(policy));
175     }
176
177     private boolean checkTransient(Policy policy) {
178         if (policy.isTransient()) {
179             this.policies.remove(policy);
180         }
181         return policy.isTransient();
182     }
183
184     private Flux<Policy> recreateAllPoliciesInRic(Ric ric, A1Client a1Client) {
185         return Flux.fromIterable(policies.getForRic(ric.id())) //
186                 .doOnNext(policy -> logger.debug("Recreating policy: {}, ric: {}", policy.getId(), ric.id())) //
187                 .filter(policy -> !checkTransient(policy)) //
188                 .flatMap(policy -> putPolicy(policy, ric, a1Client), CONCURRENCY_RIC)
189                 .doOnError(t -> logger.warn("Recreating policy failed, ric: {}, reason: {}", ric.id(), t.getMessage()));
190     }
191
192 }