Change name of policy ID in API
[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.UNDEFINED);
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.IDLE);
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()), throwable -> logger
141                             .warn("Service notification failed for service: {}", service.getName(), throwable),
142                         () -> logger.debug("All services notified"));
143             }
144         }
145     }
146
147     private Flux<Object> deleteAllPolicyInstances(Ric ric, Throwable t) {
148         logger.warn("Recreation of policies failed for ric: {}, reason: {}", ric.name(), t.getMessage());
149         deleteAllPoliciesInRepository(ric);
150
151         Flux<PolicyType> synchronizedTypes = this.a1ClientFactory.createA1Client(ric) //
152             .flatMapMany(a1Client -> synchronizePolicyTypes(ric, a1Client));
153         Flux<?> deletePoliciesInRic = this.a1ClientFactory.createA1Client(ric) //
154             .flatMapMany(A1Client::deleteAllPolicies) //
155             .doOnComplete(() -> deleteAllPoliciesInRepository(ric));
156
157         return Flux.concat(synchronizedTypes, deletePoliciesInRic);
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         for (Policy policy : policies.getForRic(ric.name())) {
189             this.policies.remove(policy);
190         }
191     }
192
193     private Flux<Policy> putPolicy(Policy policy, Ric ric, A1Client a1Client) {
194         logger.debug("Recreating policy: {}, for ric: {}", policy.id(), ric.getConfig().name());
195         return a1Client.putPolicy(policy) //
196             .flatMapMany(notUsed -> Flux.just(policy));
197     }
198
199     private Flux<Policy> recreateAllPoliciesInRic(Ric ric, A1Client a1Client) {
200         return Flux.fromIterable(policies.getForRic(ric.name())) //
201             .flatMap(policy -> putPolicy(policy, ric, a1Client));
202     }
203
204 }