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