d1bd433b91e210bc5c54279e3c3926240d427394
[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 java.util.Set;
26
27 import org.onap.ccsdk.oran.a1policymanagementservice.clients.A1Client;
28 import org.onap.ccsdk.oran.a1policymanagementservice.clients.A1ClientFactory;
29 import org.onap.ccsdk.oran.a1policymanagementservice.clients.AsyncRestClientFactory;
30 import org.onap.ccsdk.oran.a1policymanagementservice.controllers.ServiceCallbacks;
31 import org.onap.ccsdk.oran.a1policymanagementservice.repository.Policies;
32 import org.onap.ccsdk.oran.a1policymanagementservice.repository.Policy;
33 import org.onap.ccsdk.oran.a1policymanagementservice.repository.PolicyType;
34 import org.onap.ccsdk.oran.a1policymanagementservice.repository.PolicyTypes;
35 import org.onap.ccsdk.oran.a1policymanagementservice.repository.Ric;
36 import org.onap.ccsdk.oran.a1policymanagementservice.repository.Rics;
37 import org.onap.ccsdk.oran.a1policymanagementservice.repository.Services;
38 import org.slf4j.Logger;
39 import org.slf4j.LoggerFactory;
40 import org.springframework.web.reactive.function.client.WebClientResponseException;
41
42 import reactor.core.publisher.Flux;
43 import reactor.core.publisher.Mono;
44 import reactor.core.publisher.SignalType;
45
46 /**
47  * Synchronizes the content of a Near-RT RIC with the content in the repository.
48  * This means:
49  * <p>
50  * load all policy types
51  * <p>
52  * send all policy instances to the Near-RT RIC
53  * <p>
54  * if that fails remove all policy instances
55  * <p>
56  * Notify subscribing services
57  */
58 @SuppressWarnings("squid:S2629") // Invoke method(s) only conditionally
59 public class RicSynchronizationTask {
60
61     private static final Logger logger = LoggerFactory.getLogger(RicSynchronizationTask.class);
62     static final int CONCURRENCY_RIC = 1; // How many paralell requests that is sent to one NearRT RIC
63
64     private final A1ClientFactory a1ClientFactory;
65     private final PolicyTypes policyTypes;
66     private final Policies policies;
67     private final Services services;
68     private final Rics rics;
69     private final AsyncRestClientFactory restClientFactory;
70
71     public RicSynchronizationTask(A1ClientFactory a1ClientFactory, PolicyTypes policyTypes, Policies policies,
72             Services services, AsyncRestClientFactory restClientFactory, Rics rics) {
73         this.a1ClientFactory = a1ClientFactory;
74         this.policyTypes = policyTypes;
75         this.policies = policies;
76         this.services = services;
77         this.restClientFactory = restClientFactory;
78         this.rics = rics;
79     }
80
81     public Mono<Ric> synchronizeRic(Ric ric) {
82         if (ric.getLock().getLockCounter() != 1) {
83             logger.error("Exclusive lock is required to run synchronization, ric: {}", ric.id());
84             return Mono.empty();
85         }
86         return this.a1ClientFactory.createA1Client(ric) //
87                 .doOnNext(client -> ric.setState(RicState.SYNCHRONIZING)) //
88                 .flatMapMany(client -> runSynchronization(ric, client)) //
89                 .doOnError(t -> { //
90                     logger.warn("Synchronization failure for ric: {}, reason: {}", ric.id(), t.getMessage()); //
91                     deletePoliciesIfNotRecreatable(t, ric);
92                 }) //
93                 .collectList() //
94                 .flatMap(notUsed -> onSynchronizationComplete(ric)) //
95                 .onErrorResume(t -> Mono.just(ric)) //
96                 .doFinally(signal -> onFinally(signal, ric));
97     }
98
99     private void onFinally(SignalType signal, Ric ric) {
100         if (ric.getState().equals(RicState.SYNCHRONIZING)) {
101             logger.debug("Resetting ric state after failed synch, ric: {}, signal: {}", ric.id(), signal);
102             ric.setState(RicState.UNAVAILABLE); //
103         }
104     }
105
106     /**
107      * If a 4xx error is received, allpolicies are deleted. This is just to avoid
108      * cyclical receovery due to that the NearRT RIC cannot accept a previously
109      * policy.
110      */
111     private void deletePoliciesIfNotRecreatable(Throwable throwable, Ric ric) {
112         if (throwable instanceof WebClientResponseException) {
113             WebClientResponseException responseException = (WebClientResponseException) throwable;
114             if (responseException.getStatusCode().is4xxClientError()) {
115                 deleteAllPoliciesInRepository(ric);
116             }
117         }
118     }
119
120     private void deleteAllPoliciesInRepository(Ric ric) {
121         for (Policy policy : policies.getForRic(ric.id())) {
122             this.policies.remove(policy);
123         }
124     }
125
126     public Flux<PolicyType> synchronizePolicyTypes(Ric ric, A1Client a1Client) {
127         return a1Client.getPolicyTypeIdentities() //
128                 .doOnNext(x -> ric.clearSupportedPolicyTypes()) //
129                 .flatMapMany(Flux::fromIterable) //
130                 .doOnNext(typeId -> logger.debug("For ric: {}, handling type: {}", ric.getConfig().getRicId(), typeId)) //
131                 .flatMap(policyTypeId -> getPolicyType(policyTypeId, a1Client), CONCURRENCY_RIC) //
132                 .doOnNext(ric::addSupportedPolicyType); //
133     }
134
135     private Flux<Object> runSynchronization(Ric ric, A1Client a1Client) {
136         Flux<PolicyType> synchronizedTypes = synchronizePolicyTypes(ric, a1Client);
137         Set<String> excludeFromDelete = this.policies.getPolicyIdsForRic(ric.id());
138         Flux<?> policiesDeletedInRic = a1Client.deleteAllPolicies(excludeFromDelete);
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 }