Merge "Added STD sim 2.0.0 tests"
[nonrtric.git] / policy-agent / src / main / java / org / oransc / policyagent / tasks / RicSynchronizationTask.java
1 /*-
2  * ========================LICENSE_START=================================
3  * O-RAN-SC
4  * %%
5  * Copyright (C) 2019 Nordix Foundation
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.oransc.policyagent.tasks;
22
23 import static org.oransc.policyagent.repository.Ric.RicState;
24
25 import org.oransc.policyagent.clients.A1Client;
26 import org.oransc.policyagent.clients.A1ClientFactory;
27 import org.oransc.policyagent.clients.AsyncRestClient;
28 import org.oransc.policyagent.repository.ImmutablePolicyType;
29 import org.oransc.policyagent.repository.Lock.LockType;
30 import org.oransc.policyagent.repository.Policies;
31 import org.oransc.policyagent.repository.Policy;
32 import org.oransc.policyagent.repository.PolicyType;
33 import org.oransc.policyagent.repository.PolicyTypes;
34 import org.oransc.policyagent.repository.Ric;
35 import org.oransc.policyagent.repository.Service;
36 import org.oransc.policyagent.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 RIC with the content in the repository. This
47  * means:
48  * <p>
49  * load all policy types
50  * <p>
51  * send all policy instances to the 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().name());
78
79         if (ric.getState() == RicState.SYNCHRONIZING) {
80             logger.debug("Ric: {} is already being synchronized", ric.getConfig().name());
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.name(), throwable.getMessage());
93                     ric.setState(RicState.UNAVAILABLE);
94                 }
95
96                 @Override
97                 protected void hookOnComplete() {
98                     onSynchronizationComplete(ric);
99                 }
100
101                 @Override
102                 protected void hookFinally(SignalType type) {
103                     ric.getLock().unlockBlocking();
104                 }
105             });
106     }
107
108     @SuppressWarnings("squid:S2445") // Blocks should be synchronized on "private final" fields
109     private Mono<Ric> setRicState(Ric ric) {
110         synchronized (ric) {
111             if (ric.getState() == RicState.SYNCHRONIZING) {
112                 logger.debug("Ric: {} is already being synchronized", ric.getConfig().name());
113                 return Mono.empty();
114             }
115             ric.setState(RicState.SYNCHRONIZING);
116             return Mono.just(ric);
117         }
118     }
119
120     private Flux<Object> runSynchronization(Ric ric, A1Client a1Client) {
121         Flux<PolicyType> synchronizedTypes = synchronizePolicyTypes(ric, a1Client);
122         Flux<?> policiesDeletedInRic = a1Client.deleteAllPolicies();
123         Flux<Policy> policiesRecreatedInRic = recreateAllPoliciesInRic(ric, a1Client);
124
125         return Flux.concat(synchronizedTypes, policiesDeletedInRic, policiesRecreatedInRic);
126     }
127
128     private void onSynchronizationComplete(Ric ric) {
129         logger.debug("Synchronization completed for: {}", ric.name());
130         ric.setState(RicState.AVAILABLE);
131         notifyAllServices("Synchronization completed for:" + ric.name());
132     }
133
134     private void notifyAllServices(String body) {
135         for (Service service : services.getAll()) {
136             String url = service.getCallbackUrl();
137             if (url.length() > 0) {
138                 createNotificationClient(url) //
139                     .put("", body) //
140                     .subscribe( //
141                         notUsed -> logger.debug("Service {} notified", service.getName()),
142                         throwable -> logger.warn("Service notification failed for service: {}. Cause: {}",
143                             service.getName(), throwable.getMessage()),
144                         () -> logger.debug("All services notified"));
145             }
146         }
147     }
148
149     private Flux<Object> deleteAllPolicyInstances(Ric ric, Throwable t) {
150         logger.debug("Recreation of policies failed for ric: {}, reason: {}", ric.name(), t.getMessage());
151         deleteAllPoliciesInRepository(ric);
152
153         Flux<PolicyType> synchronizedTypes = this.a1ClientFactory.createA1Client(ric) //
154             .flatMapMany(a1Client -> synchronizePolicyTypes(ric, a1Client));
155         Flux<?> deletePoliciesInRic = this.a1ClientFactory.createA1Client(ric) //
156             .flatMapMany(A1Client::deleteAllPolicies) //
157             .doOnComplete(() -> deleteAllPoliciesInRepository(ric));
158
159         return Flux.concat(synchronizedTypes, deletePoliciesInRic);
160     }
161
162     AsyncRestClient createNotificationClient(final String url) {
163         return new AsyncRestClient(url, this.a1ClientFactory.getAppConfig().getWebClientConfig());
164     }
165
166     private Flux<PolicyType> synchronizePolicyTypes(Ric ric, A1Client a1Client) {
167         return a1Client.getPolicyTypeIdentities() //
168             .doOnNext(x -> ric.clearSupportedPolicyTypes()) //
169             .flatMapMany(Flux::fromIterable) //
170             .doOnNext(typeId -> logger.debug("For ric: {}, handling type: {}", ric.getConfig().name(), typeId)) //
171             .flatMap(policyTypeId -> getPolicyType(policyTypeId, a1Client), CONCURRENCY_RIC) //
172             .doOnNext(ric::addSupportedPolicyType); //
173     }
174
175     private Mono<PolicyType> getPolicyType(String policyTypeId, A1Client a1Client) {
176         if (policyTypes.contains(policyTypeId)) {
177             return Mono.just(policyTypes.get(policyTypeId));
178         }
179         return a1Client.getPolicyTypeSchema(policyTypeId) //
180             .flatMap(schema -> createPolicyType(policyTypeId, schema));
181     }
182
183     private Mono<PolicyType> createPolicyType(String policyTypeId, String schema) {
184         PolicyType pt = ImmutablePolicyType.builder().name(policyTypeId).schema(schema).build();
185         policyTypes.put(pt);
186         return Mono.just(pt);
187     }
188
189     private void deleteAllPoliciesInRepository(Ric ric) {
190         for (Policy policy : policies.getForRic(ric.name())) {
191             this.policies.remove(policy);
192         }
193     }
194
195     private Flux<Policy> putPolicy(Policy policy, Ric ric, A1Client a1Client) {
196         logger.debug("Recreating policy: {}, for ric: {}", policy.id(), ric.getConfig().name());
197         return a1Client.putPolicy(policy) //
198             .flatMapMany(notUsed -> Flux.just(policy));
199     }
200
201     private boolean checkTransient(Policy policy) {
202         if (policy.isTransient()) {
203             this.policies.remove(policy);
204         }
205         return policy.isTransient();
206     }
207
208     private Flux<Policy> recreateAllPoliciesInRic(Ric ric, A1Client a1Client) {
209         return Flux.fromIterable(policies.getForRic(ric.name())) //
210             .filter(policy -> !checkTransient(policy)) //
211             .flatMap(policy -> putPolicy(policy, ric, a1Client), CONCURRENCY_RIC);
212     }
213
214 }