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