2 * ========================LICENSE_START=================================
5 * Copyright (C) 2019 Nordix Foundation
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
11 * http://www.apache.org/licenses/LICENSE-2.0
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===================================
21 package org.oransc.policyagent.tasks;
23 import static org.oransc.policyagent.repository.Ric.RicState;
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;
40 import reactor.core.publisher.BaseSubscriber;
41 import reactor.core.publisher.Flux;
42 import reactor.core.publisher.Mono;
43 import reactor.core.publisher.SignalType;
46 * Synchronizes the content of a RIC with the content in the repository. This
49 * load all policy types
51 * send all policy instances to the RIC
53 * if that fails remove all policy instances
55 * Notify subscribing services
57 @SuppressWarnings("squid:S2629") // Invoke method(s) only conditionally
58 public class RicSynchronizationTask {
60 private static final Logger logger = LoggerFactory.getLogger(RicSynchronizationTask.class);
61 static final int CONCURRENCY_RIC = 1; // How may paralell requests that is sent to one NearRT RIC
63 private final A1ClientFactory a1ClientFactory;
64 private final PolicyTypes policyTypes;
65 private final Policies policies;
66 private final Services services;
68 public RicSynchronizationTask(A1ClientFactory a1ClientFactory, PolicyTypes policyTypes, Policies policies,
70 this.a1ClientFactory = a1ClientFactory;
71 this.policyTypes = policyTypes;
72 this.policies = policies;
73 this.services = services;
76 public void run(Ric ric) {
77 logger.debug("Handling ric: {}", ric.getConfig().name());
79 if (ric.getState() == RicState.SYNCHRONIZING) {
80 logger.debug("Ric: {} is already being synchronized", ric.getConfig().name());
84 ric.getLock().lock(LockType.EXCLUSIVE) //
85 .flatMap(notUsed -> setRicState(ric)) //
86 .flatMap(lock -> this.a1ClientFactory.createA1Client(ric)) //
87 .flatMapMany(client -> runSynchronization(ric, client)) //
88 .onErrorResume(throwable -> deleteAllPolicyInstances(ric, throwable))
89 .subscribe(new BaseSubscriber<Object>() {
91 protected void hookOnError(Throwable throwable) {
92 logger.warn("Synchronization failure for ric: {}, reason: {}", ric.name(), throwable.getMessage());
93 ric.setState(RicState.UNAVAILABLE);
97 protected void hookOnComplete() {
98 onSynchronizationComplete(ric);
102 protected void hookFinally(SignalType type) {
103 ric.getLock().unlockBlocking();
108 @SuppressWarnings("squid:S2445") // Blocks should be synchronized on "private final" fields
109 private Mono<Ric> setRicState(Ric ric) {
111 if (ric.getState() == RicState.SYNCHRONIZING) {
112 logger.debug("Ric: {} is already being synchronized", ric.getConfig().name());
115 ric.setState(RicState.SYNCHRONIZING);
116 return Mono.just(ric);
120 private Flux<Object> runSynchronization(Ric ric, A1Client a1Client) {
121 Flux<PolicyType> synchronizedTypes = synchronizePolicyTypes(ric, a1Client);
122 Flux<?> policiesDeletedInRic = a1Client.deleteAllPolicies();
123 Flux<Policy> policiesRecreatedInRic = recreateAllPoliciesInRic(ric, a1Client);
125 return Flux.concat(synchronizedTypes, policiesDeletedInRic, policiesRecreatedInRic);
128 private void onSynchronizationComplete(Ric ric) {
129 logger.debug("Synchronization completed for: {}", ric.name());
130 ric.setState(RicState.AVAILABLE);
131 notifyAllServices("Synchronization completed for:" + ric.name());
134 private void notifyAllServices(String body) {
135 for (Service service : services.getAll()) {
136 String url = service.getCallbackUrl();
137 if (url.length() > 0) {
138 createNotificationClient(url) //
141 notUsed -> logger.debug("Service {} notified", service.getName()),
142 throwable -> logger.warn("Service notification failed for service: {}. Cause: {}",
143 service.getName(), throwable.getMessage()),
144 () -> logger.debug("All services notified"));
149 private Flux<Object> deleteAllPolicyInstances(Ric ric, Throwable t) {
150 logger.debug("Recreation of policies failed for ric: {}, reason: {}", ric.name(), t.getMessage());
151 deleteAllPoliciesInRepository(ric);
153 Flux<PolicyType> synchronizedTypes = this.a1ClientFactory.createA1Client(ric) //
154 .flatMapMany(a1Client -> synchronizePolicyTypes(ric, a1Client));
155 Flux<?> deletePoliciesInRic = this.a1ClientFactory.createA1Client(ric) //
156 .flatMapMany(A1Client::deleteAllPolicies) //
157 .doOnComplete(() -> deleteAllPoliciesInRepository(ric));
159 return Flux.concat(synchronizedTypes, deletePoliciesInRic);
162 AsyncRestClient createNotificationClient(final String url) {
163 return new AsyncRestClient(url);
166 private Flux<PolicyType> synchronizePolicyTypes(Ric ric, A1Client a1Client) {
167 return a1Client.getPolicyTypeIdentities() //
168 .doOnNext(x -> ric.clearSupportedPolicyTypes()) //
169 .flatMapMany(Flux::fromIterable) //
170 .doOnNext(typeId -> logger.debug("For ric: {}, handling type: {}", ric.getConfig().name(), typeId)) //
171 .flatMap(policyTypeId -> getPolicyType(policyTypeId, a1Client), CONCURRENCY_RIC) //
172 .doOnNext(ric::addSupportedPolicyType); //
175 private Mono<PolicyType> getPolicyType(String policyTypeId, A1Client a1Client) {
176 if (policyTypes.contains(policyTypeId)) {
177 return Mono.just(policyTypes.get(policyTypeId));
179 return a1Client.getPolicyTypeSchema(policyTypeId) //
180 .flatMap(schema -> createPolicyType(policyTypeId, schema));
183 private Mono<PolicyType> createPolicyType(String policyTypeId, String schema) {
184 PolicyType pt = ImmutablePolicyType.builder().name(policyTypeId).schema(schema).build();
186 return Mono.just(pt);
189 private void deleteAllPoliciesInRepository(Ric ric) {
190 for (Policy policy : policies.getForRic(ric.name())) {
191 this.policies.remove(policy);
195 private Flux<Policy> putPolicy(Policy policy, Ric ric, A1Client a1Client) {
196 logger.debug("Recreating policy: {}, for ric: {}", policy.id(), ric.getConfig().name());
197 return a1Client.putPolicy(policy) //
198 .flatMapMany(notUsed -> Flux.just(policy));
201 private boolean checkTransient(Policy policy) {
202 if (policy.isTransient()) {
203 this.policies.remove(policy);
205 return policy.isTransient();
208 private Flux<Policy> recreateAllPoliciesInRic(Ric ric, A1Client a1Client) {
209 return Flux.fromIterable(policies.getForRic(ric.name())) //
210 .filter(policy -> !checkTransient(policy)) //
211 .flatMap(policy -> putPolicy(policy, ric, a1Client), CONCURRENCY_RIC);