Fixed concurrency problems
[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.Vector;
26
27 import org.oransc.policyagent.clients.A1Client;
28 import org.oransc.policyagent.clients.A1ClientFactory;
29 import org.oransc.policyagent.clients.AsyncRestClient;
30 import org.oransc.policyagent.repository.ImmutablePolicyType;
31 import org.oransc.policyagent.repository.Lock.LockType;
32 import org.oransc.policyagent.repository.Policies;
33 import org.oransc.policyagent.repository.Policy;
34 import org.oransc.policyagent.repository.PolicyType;
35 import org.oransc.policyagent.repository.PolicyTypes;
36 import org.oransc.policyagent.repository.Ric;
37 import org.oransc.policyagent.repository.Service;
38 import org.oransc.policyagent.repository.Services;
39 import org.slf4j.Logger;
40 import org.slf4j.LoggerFactory;
41
42 import reactor.core.publisher.Flux;
43 import reactor.core.publisher.Mono;
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 public class RicSynchronizationTask {
58
59     private static final Logger logger = LoggerFactory.getLogger(RicSynchronizationTask.class);
60
61     private final A1ClientFactory a1ClientFactory;
62     private final PolicyTypes policyTypes;
63     private final Policies policies;
64     private final Services services;
65
66     public RicSynchronizationTask(A1ClientFactory a1ClientFactory, PolicyTypes policyTypes, Policies policies,
67         Services services) {
68         this.a1ClientFactory = a1ClientFactory;
69         this.policyTypes = policyTypes;
70         this.policies = policies;
71         this.services = services;
72     }
73
74     @SuppressWarnings("squid:S2629")
75     public void run(Ric ric) {
76         logger.debug("Handling ric: {}", ric.getConfig().name());
77
78         synchronized (ric) {
79             if (ric.getState() == RicState.SYNCHRONIZING) {
80                 logger.debug("Ric: {} is already being synchronized", ric.getConfig().name());
81                 return;
82             }
83             ric.setState(RicState.SYNCHRONIZING);
84         }
85         ric.getLock().lockBlocking(LockType.EXCLUSIVE); // Make sure no NBI updates are running
86         ric.getLock().unlock();
87         this.a1ClientFactory.createA1Client(ric)//
88             .flatMapMany(client -> startSynchronization(ric, client)) //
89             .subscribe(x -> logger.debug("Synchronize: {}", x), //
90                 throwable -> onSynchronizationError(ric, throwable), //
91                 () -> onSynchronizationComplete(ric));
92     }
93
94     private Flux<Object> startSynchronization(Ric ric, A1Client a1Client) {
95         Flux<PolicyType> recoverTypes = synchronizePolicyTypes(ric, a1Client);
96         Flux<?> policiesDeletedInRic = a1Client.deleteAllPolicies();
97         Flux<?> policiesRecreatedInRic = recreateAllPoliciesInRic(ric, a1Client);
98
99         return Flux.concat(recoverTypes, policiesDeletedInRic, policiesRecreatedInRic);
100     }
101
102     @SuppressWarnings("squid:S2629")
103     private void onSynchronizationComplete(Ric ric) {
104         logger.debug("Synchronization completed for: {}", ric.name());
105         ric.setState(RicState.IDLE);
106         notifyAllServices("Synchronization completed for:" + ric.name());
107     }
108
109     private void notifyAllServices(String body) {
110         synchronized (services) {
111             for (Service service : services.getAll()) {
112                 String url = service.getCallbackUrl();
113                 if (service.getCallbackUrl().length() > 0) {
114                     createNotificationClient(url) //
115                         .put("", body) //
116                         .subscribe(
117                             notUsed -> logger.debug("Service {} notified", service.getName()), throwable -> logger
118                                 .warn("Service notification failed for service: {}", service.getName(), throwable),
119                             () -> logger.debug("All services notified"));
120                 }
121             }
122         }
123     }
124
125     @SuppressWarnings("squid:S2629")
126     private void onSynchronizationError(Ric ric, Throwable t) {
127         logger.warn("Synchronization failed for ric: {}, reason: {}", ric.name(), t.getMessage());
128         // If recovery fails, try to remove all instances
129         deleteAllPoliciesInRepository(ric);
130
131         Flux<PolicyType> recoverTypes = this.a1ClientFactory.createA1Client(ric) //
132             .flatMapMany(a1Client -> synchronizePolicyTypes(ric, a1Client));
133         Flux<?> deletePoliciesInRic = this.a1ClientFactory.createA1Client(ric) //
134             .flatMapMany(a1Client -> a1Client.deleteAllPolicies()) //
135             .doOnComplete(() -> deleteAllPoliciesInRepository(ric));
136
137         Flux.concat(recoverTypes, deletePoliciesInRic) //
138             .subscribe(x -> logger.debug("Brute recover: " + x), //
139                 throwable -> onRecoveryError(ric, throwable), //
140                 () -> onSynchronizationComplete(ric));
141     }
142
143     @SuppressWarnings("squid:S2629")
144     private void onRecoveryError(Ric ric, Throwable t) {
145         logger.warn("Synchronization failure recovery failed for ric: {}, reason: {}", ric.name(), t.getMessage());
146         ric.setState(RicState.UNDEFINED);
147     }
148
149     AsyncRestClient createNotificationClient(final String url) {
150         return new AsyncRestClient(url);
151     }
152
153     private Flux<PolicyType> synchronizePolicyTypes(Ric ric, A1Client a1Client) {
154         return a1Client.getPolicyTypeIdentities() //
155             .doOnNext(x -> ric.clearSupportedPolicyTypes()) //
156             .flatMapMany(Flux::fromIterable) //
157             .doOnNext(typeId -> logger.debug("For ric: {}, handling type: {}", ric.getConfig().name(), typeId)) //
158             .flatMap(policyTypeId -> getPolicyType(policyTypeId, a1Client)) //
159             .doOnNext(ric::addSupportedPolicyType); //
160     }
161
162     private Mono<PolicyType> getPolicyType(String policyTypeId, A1Client a1Client) {
163         if (policyTypes.contains(policyTypeId)) {
164             return Mono.just(policyTypes.get(policyTypeId));
165         }
166         return a1Client.getPolicyTypeSchema(policyTypeId) //
167             .flatMap(schema -> createPolicyType(policyTypeId, schema));
168     }
169
170     private Mono<PolicyType> createPolicyType(String policyTypeId, String schema) {
171         PolicyType pt = ImmutablePolicyType.builder().name(policyTypeId).schema(schema).build();
172         policyTypes.put(pt);
173         return Mono.just(pt);
174     }
175
176     private void deleteAllPoliciesInRepository(Ric ric) {
177         synchronized (policies) {
178             for (Policy policy : policies.getForRic(ric.name())) {
179                 this.policies.remove(policy);
180             }
181         }
182     }
183
184     private Flux<String> recreateAllPoliciesInRic(Ric ric, A1Client a1Client) {
185         synchronized (policies) {
186             return Flux.fromIterable(new Vector<>(policies.getForRic(ric.name()))) //
187                 .doOnNext(
188                     policy -> logger.debug("Recreating policy: {}, for ric: {}", policy.id(), ric.getConfig().name()))
189                 .flatMap(a1Client::putPolicy);
190         }
191     }
192
193 }