df0771cb1aac74840ee3515543eabc1f19fbbbbe
[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.AsyncRestClient;
28 import org.onap.ccsdk.oran.a1policymanagementservice.clients.AsyncRestClientFactory;
29 import org.onap.ccsdk.oran.a1policymanagementservice.configuration.ApplicationConfig;
30 import org.onap.ccsdk.oran.a1policymanagementservice.repository.ImmutablePolicyType;
31 import org.onap.ccsdk.oran.a1policymanagementservice.repository.Lock.LockType;
32 import org.onap.ccsdk.oran.a1policymanagementservice.repository.Policies;
33 import org.onap.ccsdk.oran.a1policymanagementservice.repository.Policy;
34 import org.onap.ccsdk.oran.a1policymanagementservice.repository.PolicyType;
35 import org.onap.ccsdk.oran.a1policymanagementservice.repository.PolicyTypes;
36 import org.onap.ccsdk.oran.a1policymanagementservice.repository.Ric;
37 import org.onap.ccsdk.oran.a1policymanagementservice.repository.Service;
38 import org.onap.ccsdk.oran.a1policymanagementservice.repository.Services;
39 import org.slf4j.Logger;
40 import org.slf4j.LoggerFactory;
41
42 import reactor.core.publisher.BaseSubscriber;
43 import reactor.core.publisher.Flux;
44 import reactor.core.publisher.Mono;
45 import reactor.core.publisher.SignalType;
46
47 /**
48  * Synchronizes the content of a Near-RT RIC with the content in the repository.
49  * This means:
50  * <p>
51  * load all policy types
52  * <p>
53  * send all policy instances to the Near-RT RIC
54  * <p>
55  * if that fails remove all policy instances
56  * <p>
57  * Notify subscribing services
58  */
59 @SuppressWarnings("squid:S2629") // Invoke method(s) only conditionally
60 public class RicSynchronizationTask {
61
62     private static final Logger logger = LoggerFactory.getLogger(RicSynchronizationTask.class);
63     static final int CONCURRENCY_RIC = 1; // How may paralell requests that is sent to one NearRT RIC
64
65     private final A1ClientFactory a1ClientFactory;
66     private final PolicyTypes policyTypes;
67     private final Policies policies;
68     private final Services services;
69     private final AsyncRestClientFactory restClientFactory;
70
71     public RicSynchronizationTask(A1ClientFactory a1ClientFactory, PolicyTypes policyTypes, Policies policies,
72             Services services, ApplicationConfig config) {
73         this.a1ClientFactory = a1ClientFactory;
74         this.policyTypes = policyTypes;
75         this.policies = policies;
76         this.services = services;
77         this.restClientFactory = new AsyncRestClientFactory(config.getWebClientConfig());
78     }
79
80     public void run(Ric ric) {
81         logger.debug("Handling ric: {}", ric.getConfig().ricId());
82
83         if (ric.getState() == RicState.SYNCHRONIZING) {
84             logger.debug("Ric: {} is already being synchronized", ric.getConfig().ricId());
85             return;
86         }
87
88         ric.getLock().lock(LockType.EXCLUSIVE) //
89                 .flatMap(notUsed -> setRicState(ric)) //
90                 .flatMap(lock -> this.a1ClientFactory.createA1Client(ric)) //
91                 .flatMapMany(client -> runSynchronization(ric, client)) //
92                 .onErrorResume(throwable -> deleteAllPolicyInstances(ric, throwable))
93                 .subscribe(new BaseSubscriber<Object>() {
94                     @Override
95                     protected void hookOnError(Throwable throwable) {
96                         logger.warn("Synchronization failure for ric: {}, reason: {}", ric.id(),
97                                 throwable.getMessage());
98                         ric.setState(RicState.UNAVAILABLE);
99                     }
100
101                     @Override
102                     protected void hookOnComplete() {
103                         onSynchronizationComplete(ric);
104                     }
105
106                     @Override
107                     protected void hookFinally(SignalType type) {
108                         ric.getLock().unlockBlocking();
109                     }
110                 });
111     }
112
113     @SuppressWarnings("squid:S2445") // Blocks should be synchronized on "private final" fields
114     private Mono<Ric> setRicState(Ric ric) {
115         synchronized (ric) {
116             if (ric.getState() == RicState.SYNCHRONIZING) {
117                 logger.debug("Ric: {} is already being synchronized", ric.getConfig().ricId());
118                 return Mono.empty();
119             }
120             ric.setState(RicState.SYNCHRONIZING);
121             return Mono.just(ric);
122         }
123     }
124
125     private Flux<Object> runSynchronization(Ric ric, A1Client a1Client) {
126         Flux<PolicyType> synchronizedTypes = synchronizePolicyTypes(ric, a1Client);
127         Flux<?> policiesDeletedInRic = a1Client.deleteAllPolicies();
128         Flux<Policy> policiesRecreatedInRic = recreateAllPoliciesInRic(ric, a1Client);
129
130         return Flux.concat(synchronizedTypes, policiesDeletedInRic, policiesRecreatedInRic);
131     }
132
133     private void onSynchronizationComplete(Ric ric) {
134         logger.debug("Synchronization completed for: {}", ric.id());
135         ric.setState(RicState.AVAILABLE);
136         notifyAllServices("Synchronization completed for:" + ric.id());
137     }
138
139     private void notifyAllServices(String body) {
140         for (Service service : services.getAll()) {
141             String url = service.getCallbackUrl();
142             if (url.length() > 0) {
143                 createNotificationClient(url) //
144                         .put("", body) //
145                         .subscribe( //
146                                 notUsed -> logger.debug("Service {} notified", service.getName()),
147                                 throwable -> logger.warn("Service notification failed for service: {}. Cause: {}",
148                                         service.getName(), throwable.getMessage()),
149                                 () -> logger.debug("All services notified"));
150             }
151         }
152     }
153
154     private Flux<Object> deleteAllPolicyInstances(Ric ric, Throwable t) {
155         logger.debug("Recreation of policies failed for ric: {}, reason: {}", ric.id(), t.getMessage());
156         deleteAllPoliciesInRepository(ric);
157
158         Flux<PolicyType> synchronizedTypes = this.a1ClientFactory.createA1Client(ric) //
159                 .flatMapMany(a1Client -> synchronizePolicyTypes(ric, a1Client));
160         Flux<?> deletePoliciesInRic = this.a1ClientFactory.createA1Client(ric) //
161                 .flatMapMany(A1Client::deleteAllPolicies) //
162                 .doOnComplete(() -> deleteAllPoliciesInRepository(ric));
163
164         return Flux.concat(synchronizedTypes, deletePoliciesInRic);
165     }
166
167     AsyncRestClient createNotificationClient(final String url) {
168         return restClientFactory.createRestClient(url);
169     }
170
171     private Flux<PolicyType> synchronizePolicyTypes(Ric ric, A1Client a1Client) {
172         return a1Client.getPolicyTypeIdentities() //
173                 .doOnNext(x -> ric.clearSupportedPolicyTypes()) //
174                 .flatMapMany(Flux::fromIterable) //
175                 .doOnNext(typeId -> logger.debug("For ric: {}, handling type: {}", ric.getConfig().ricId(), typeId)) //
176                 .flatMap(policyTypeId -> getPolicyType(policyTypeId, a1Client), CONCURRENCY_RIC) //
177                 .doOnNext(ric::addSupportedPolicyType); //
178     }
179
180     private Mono<PolicyType> getPolicyType(String policyTypeId, A1Client a1Client) {
181         if (policyTypes.contains(policyTypeId)) {
182             return Mono.just(policyTypes.get(policyTypeId));
183         }
184         return a1Client.getPolicyTypeSchema(policyTypeId) //
185                 .flatMap(schema -> createPolicyType(policyTypeId, schema));
186     }
187
188     private Mono<PolicyType> createPolicyType(String policyTypeId, String schema) {
189         PolicyType pt = ImmutablePolicyType.builder().id(policyTypeId).schema(schema).build();
190         policyTypes.put(pt);
191         return Mono.just(pt);
192     }
193
194     private void deleteAllPoliciesInRepository(Ric ric) {
195         for (Policy policy : policies.getForRic(ric.id())) {
196             this.policies.remove(policy);
197         }
198     }
199
200     private Flux<Policy> putPolicy(Policy policy, Ric ric, A1Client a1Client) {
201         logger.debug("Recreating policy: {}, for ric: {}", policy.id(), ric.getConfig().ricId());
202         return a1Client.putPolicy(policy) //
203                 .flatMapMany(notUsed -> Flux.just(policy));
204     }
205
206     private boolean checkTransient(Policy policy) {
207         if (policy.isTransient()) {
208             this.policies.remove(policy);
209         }
210         return policy.isTransient();
211     }
212
213     private Flux<Policy> recreateAllPoliciesInRic(Ric ric, A1Client a1Client) {
214         return Flux.fromIterable(policies.getForRic(ric.id())) //
215                 .filter(policy -> !checkTransient(policy)) //
216                 .flatMap(policy -> putPolicy(policy, ric, a1Client), CONCURRENCY_RIC);
217     }
218
219 }