Loading of configuration
[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
62     private final A1ClientFactory a1ClientFactory;
63     private final PolicyTypes policyTypes;
64     private final Policies policies;
65     private final Services services;
66
67     public RicSynchronizationTask(A1ClientFactory a1ClientFactory, PolicyTypes policyTypes, Policies policies,
68         Services services) {
69         this.a1ClientFactory = a1ClientFactory;
70         this.policyTypes = policyTypes;
71         this.policies = policies;
72         this.services = services;
73     }
74
75     public void run(Ric ric) {
76         logger.debug("Handling ric: {}", ric.getConfig().name());
77
78         if (ric.getState() == RicState.SYNCHRONIZING) {
79             logger.debug("Ric: {} is already being synchronized", ric.getConfig().name());
80             return;
81         }
82
83         ric.getLock().lock(LockType.EXCLUSIVE) //
84             .flatMap(notUsed -> setRicState(ric)) //
85             .flatMap(lock -> this.a1ClientFactory.createA1Client(ric)) //
86             .flatMapMany(client -> runSynchronization(ric, client)) //
87             .onErrorResume(throwable -> deleteAllPolicyInstances(ric, throwable))
88             .subscribe(new BaseSubscriber<Object>() {
89                 @Override
90                 protected void hookOnError(Throwable throwable) {
91                     logger.warn("Synchronization failure for ric: {}, reason: {}", ric.name(), throwable.getMessage());
92                     ric.setState(RicState.UNAVAILABLE);
93                 }
94
95                 @Override
96                 protected void hookOnComplete() {
97                     onSynchronizationComplete(ric);
98                 }
99
100                 @Override
101                 protected void hookFinally(SignalType type) {
102                     ric.getLock().unlockBlocking();
103                 }
104             });
105     }
106
107     @SuppressWarnings("squid:S2445") // Blocks should be synchronized on "private final" fields
108     private Mono<Ric> setRicState(Ric ric) {
109         synchronized (ric) {
110             if (ric.getState() == RicState.SYNCHRONIZING) {
111                 logger.debug("Ric: {} is already being synchronized", ric.getConfig().name());
112                 return Mono.empty();
113             }
114             ric.setState(RicState.SYNCHRONIZING);
115             return Mono.just(ric);
116         }
117     }
118
119     private Flux<Object> runSynchronization(Ric ric, A1Client a1Client) {
120         Flux<PolicyType> synchronizedTypes = synchronizePolicyTypes(ric, a1Client);
121         Flux<?> policiesDeletedInRic = a1Client.deleteAllPolicies();
122         Flux<Policy> policiesRecreatedInRic = recreateAllPoliciesInRic(ric, a1Client);
123
124         return Flux.concat(synchronizedTypes, policiesDeletedInRic, policiesRecreatedInRic);
125     }
126
127     private void onSynchronizationComplete(Ric ric) {
128         logger.debug("Synchronization completed for: {}", ric.name());
129         ric.setState(RicState.AVAILABLE);
130         notifyAllServices("Synchronization completed for:" + ric.name());
131     }
132
133     private void notifyAllServices(String body) {
134         for (Service service : services.getAll()) {
135             String url = service.getCallbackUrl();
136             if (service.getCallbackUrl().length() > 0) {
137                 createNotificationClient(url) //
138                     .put("", body) //
139                     .subscribe( //
140                         notUsed -> logger.debug("Service {} notified", service.getName()),
141                         throwable -> logger.warn("Service notification failed for service: {}. Cause: {}",
142                             service.getName(), throwable.getMessage()),
143                         () -> logger.debug("All services notified"));
144             }
145         }
146     }
147
148     private Flux<Object> deleteAllPolicyInstances(Ric ric, Throwable t) {
149         logger.debug("Recreation of policies failed for ric: {}, reason: {}", ric.name(), t.getMessage());
150         deleteAllPoliciesInRepository(ric);
151
152         Flux<PolicyType> synchronizedTypes = this.a1ClientFactory.createA1Client(ric) //
153             .flatMapMany(a1Client -> synchronizePolicyTypes(ric, a1Client));
154         Flux<?> deletePoliciesInRic = this.a1ClientFactory.createA1Client(ric) //
155             .flatMapMany(A1Client::deleteAllPolicies) //
156             .doOnComplete(() -> deleteAllPoliciesInRepository(ric));
157
158         return Flux.concat(synchronizedTypes, deletePoliciesInRic);
159     }
160
161     AsyncRestClient createNotificationClient(final String url) {
162         return new AsyncRestClient(url);
163     }
164
165     private Flux<PolicyType> synchronizePolicyTypes(Ric ric, A1Client a1Client) {
166         return a1Client.getPolicyTypeIdentities() //
167             .doOnNext(x -> ric.clearSupportedPolicyTypes()) //
168             .flatMapMany(Flux::fromIterable) //
169             .doOnNext(typeId -> logger.debug("For ric: {}, handling type: {}", ric.getConfig().name(), typeId)) //
170             .flatMap(policyTypeId -> getPolicyType(policyTypeId, a1Client)) //
171             .doOnNext(ric::addSupportedPolicyType); //
172     }
173
174     private Mono<PolicyType> getPolicyType(String policyTypeId, A1Client a1Client) {
175         if (policyTypes.contains(policyTypeId)) {
176             return Mono.just(policyTypes.get(policyTypeId));
177         }
178         return a1Client.getPolicyTypeSchema(policyTypeId) //
179             .flatMap(schema -> createPolicyType(policyTypeId, schema));
180     }
181
182     private Mono<PolicyType> createPolicyType(String policyTypeId, String schema) {
183         PolicyType pt = ImmutablePolicyType.builder().name(policyTypeId).schema(schema).build();
184         policyTypes.put(pt);
185         return Mono.just(pt);
186     }
187
188     private void deleteAllPoliciesInRepository(Ric ric) {
189         for (Policy policy : policies.getForRic(ric.name())) {
190             this.policies.remove(policy);
191         }
192     }
193
194     private Flux<Policy> putPolicy(Policy policy, Ric ric, A1Client a1Client) {
195         logger.debug("Recreating policy: {}, for ric: {}", policy.id(), ric.getConfig().name());
196         return a1Client.putPolicy(policy) //
197             .flatMapMany(notUsed -> Flux.just(policy));
198     }
199
200     private Flux<Policy> recreateAllPoliciesInRic(Ric ric, A1Client a1Client) {
201         return Flux.fromIterable(policies.getForRic(ric.name())) //
202             .flatMap(policy -> putPolicy(policy, ric, a1Client));
203     }
204
205 }