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