3027981506a9c37904cc5c46db4b625fbd1635b0
[ccsdk/oran.git] /
1 /*-
2  * ========================LICENSE_START=================================
3  * ONAP : ccsdk oran
4  * ======================================================================
5  * Copyright (C) 2019-2020 Nordix Foundation. All rights reserved.
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.onap.ccsdk.oran.a1policymanagementservice.tasks;
22
23 import com.google.gson.JsonObject;
24
25 import java.time.Duration;
26 import java.util.Optional;
27 import java.util.Properties;
28
29 import lombok.AccessLevel;
30 import lombok.Getter;
31
32 import org.onap.ccsdk.oran.a1policymanagementservice.clients.A1ClientFactory;
33 import org.onap.ccsdk.oran.a1policymanagementservice.clients.AsyncRestClientFactory;
34 import org.onap.ccsdk.oran.a1policymanagementservice.configuration.ApplicationConfig;
35 import org.onap.ccsdk.oran.a1policymanagementservice.configuration.ApplicationConfig.RicConfigUpdate;
36 import org.onap.ccsdk.oran.a1policymanagementservice.configuration.ApplicationConfigParser;
37 import org.onap.ccsdk.oran.a1policymanagementservice.configuration.ConfigurationFile;
38 import org.onap.ccsdk.oran.a1policymanagementservice.controllers.ServiceCallbacks;
39 import org.onap.ccsdk.oran.a1policymanagementservice.repository.Policies;
40 import org.onap.ccsdk.oran.a1policymanagementservice.repository.PolicyTypes;
41 import org.onap.ccsdk.oran.a1policymanagementservice.repository.Ric;
42 import org.onap.ccsdk.oran.a1policymanagementservice.repository.Ric.RicState;
43 import org.onap.ccsdk.oran.a1policymanagementservice.repository.Rics;
44 import org.onap.ccsdk.oran.a1policymanagementservice.repository.Services;
45 import org.onap.dcaegen2.services.sdk.rest.services.cbs.client.api.CbsClient;
46 import org.onap.dcaegen2.services.sdk.rest.services.cbs.client.api.CbsClientFactory;
47 import org.onap.dcaegen2.services.sdk.rest.services.cbs.client.api.CbsRequests;
48 import org.onap.dcaegen2.services.sdk.rest.services.cbs.client.model.CbsRequest;
49 import org.onap.dcaegen2.services.sdk.rest.services.cbs.client.model.EnvProperties;
50 import org.onap.dcaegen2.services.sdk.rest.services.model.logging.RequestDiagnosticContext;
51 import org.slf4j.Logger;
52 import org.slf4j.LoggerFactory;
53 import org.springframework.beans.factory.annotation.Autowired;
54 import org.springframework.beans.factory.annotation.Value;
55 import org.springframework.stereotype.Component;
56
57 import reactor.core.Disposable;
58 import reactor.core.publisher.Flux;
59 import reactor.core.publisher.Mono;
60 import reactor.util.annotation.Nullable;
61
62 /**
63  * Regularly refreshes the configuration from Consul or from a local
64  * configuration file.
65  */
66 @Component
67 @SuppressWarnings("squid:S2629") // Invoke method(s) only conditionally
68 public class RefreshConfigTask {
69
70     private static final Logger logger = LoggerFactory.getLogger(RefreshConfigTask.class);
71
72     @Value("#{systemEnvironment}")
73     public Properties systemEnvironment;
74
75     /**
76      * The time between refreshes of the configuration. Not final so tests can
77      * modify it.
78      */
79     private static Duration configRefreshInterval = Duration.ofMinutes(1);
80
81     final ConfigurationFile configurationFile;
82     final ApplicationConfig appConfig;
83
84     @Getter(AccessLevel.PROTECTED)
85     private Disposable refreshTask = null;
86
87     @Getter
88     private boolean isConsulUsed = false;
89
90     private final Rics rics;
91     private final A1ClientFactory a1ClientFactory;
92     private final Policies policies;
93     private final Services services;
94     private final PolicyTypes policyTypes;
95     private final AsyncRestClientFactory restClientFactory;
96
97     @Autowired
98     public RefreshConfigTask(ConfigurationFile configurationFile, ApplicationConfig appConfig, Rics rics,
99             Policies policies, Services services, PolicyTypes policyTypes, A1ClientFactory a1ClientFactory) {
100         this.configurationFile = configurationFile;
101         this.appConfig = appConfig;
102         this.rics = rics;
103         this.policies = policies;
104         this.services = services;
105         this.policyTypes = policyTypes;
106         this.a1ClientFactory = a1ClientFactory;
107         this.restClientFactory = new AsyncRestClientFactory(appConfig.getWebClientConfig());
108     }
109
110     public void start() {
111         logger.debug("Starting refreshConfigTask");
112         stop();
113         refreshTask = createRefreshTask() //
114                 .subscribe(
115                         notUsed -> logger.debug("Refreshed configuration data"), throwable -> logger
116                                 .error("Configuration refresh terminated due to exception {}", throwable.toString()),
117                         () -> logger.error("Configuration refresh terminated"));
118     }
119
120     public void stop() {
121         if (refreshTask != null) {
122             refreshTask.dispose();
123         }
124     }
125
126     Flux<RicConfigUpdate.Type> createRefreshTask() {
127         Flux<JsonObject> loadFromFile = regularInterval() //
128                 .filter(notUsed -> !this.isConsulUsed) //
129                 .flatMap(notUsed -> loadConfigurationFromFile()) //
130                 .onErrorResume(this::ignoreErrorFlux) //
131                 .doOnNext(json -> logger.debug("loadFromFile succeeded")) //
132                 .doOnTerminate(() -> logger.error("loadFromFile Terminate"));
133
134         Flux<JsonObject> loadFromConsul = regularInterval() //
135                 .flatMap(i -> getEnvironment(systemEnvironment)) //
136                 .flatMap(this::createCbsClient) //
137                 .flatMap(this::getFromCbs) //
138                 .onErrorResume(this::ignoreErrorMono) //
139                 .doOnNext(json -> logger.debug("loadFromConsul succeeded")) //
140                 .doOnNext(json -> this.isConsulUsed = true) //
141                 .doOnTerminate(() -> logger.error("loadFromConsul Terminated"));
142
143         final int CONCURRENCY = 50; // Number of RIC synched in paralell
144
145         return Flux.merge(loadFromFile, loadFromConsul) //
146                 .flatMap(this::parseConfiguration) //
147                 .flatMap(this::updateConfig, CONCURRENCY) //
148                 .flatMap(this::handleUpdatedRicConfig) //
149                 .doOnTerminate(() -> logger.error("Configuration refresh task is terminated"));
150     }
151
152     private Flux<Long> regularInterval() {
153         return Flux.interval(Duration.ZERO, configRefreshInterval) //
154                 .onBackpressureDrop() //
155                 .limitRate(1); // Limit so that only one event is emitted at a time
156     }
157
158     Mono<EnvProperties> getEnvironment(Properties systemEnvironment) {
159         return EnvironmentProcessor.readEnvironmentVariables(systemEnvironment) //
160                 .onErrorResume(t -> Mono.empty());
161     }
162
163     Mono<CbsClient> createCbsClient(EnvProperties env) {
164         return CbsClientFactory.createCbsClient(env) //
165                 .onErrorResume(this::ignoreErrorMono);
166     }
167
168     private Mono<JsonObject> getFromCbs(CbsClient cbsClient) {
169         try {
170             final CbsRequest getConfigRequest = CbsRequests.getAll(RequestDiagnosticContext.create());
171             return cbsClient.get(getConfigRequest) //
172                     .onErrorResume(this::ignoreErrorMono);
173         } catch (Exception e) {
174             return ignoreErrorMono(e);
175         }
176     }
177
178     private <R> Flux<R> ignoreErrorFlux(Throwable throwable) {
179         String errMsg = throwable.toString();
180         logger.warn("Could not refresh application configuration. {}", errMsg);
181         return Flux.empty();
182     }
183
184     private <R> Mono<R> ignoreErrorMono(Throwable throwable) {
185         String errMsg = throwable.toString();
186         logger.warn("Could not refresh application configuration. {}", errMsg);
187         return Mono.empty();
188     }
189
190     private Mono<ApplicationConfigParser.ConfigParserResult> parseConfiguration(JsonObject jsonObject) {
191         try {
192             ApplicationConfigParser parser = new ApplicationConfigParser();
193             return Mono.just(parser.parse(jsonObject));
194         } catch (Exception e) {
195             String str = e.toString();
196             logger.error("Could not parse configuration {}", str);
197             return Mono.empty();
198         }
199     }
200
201     private Flux<RicConfigUpdate> updateConfig(ApplicationConfigParser.ConfigParserResult config) {
202         return this.appConfig.setConfiguration(config);
203     }
204
205     private void removePoliciciesInRic(@Nullable Ric ric) {
206         if (ric != null) {
207             synchronizationTask().run(ric);
208         }
209     }
210
211     private RicSynchronizationTask synchronizationTask() {
212         return new RicSynchronizationTask(a1ClientFactory, policyTypes, policies, services, restClientFactory, rics);
213     }
214
215     /**
216      * for an added RIC after a restart it is nesessary to get the suypported policy
217      * types from the RIC unless a full synchronization is wanted.
218      * 
219      * @param ric the ric to get supprted types from
220      * @return the same ric
221      */
222     private Mono<Ric> trySyncronizeSupportedTypes(Ric ric) {
223         logger.debug("Synchronizing policy types for new RIC: {}", ric.id());
224         // Synchronize the policy types
225         ric.setState(RicState.SYNCHRONIZING);
226         return this.a1ClientFactory.createA1Client(ric) //
227                 .flatMapMany(client -> synchronizationTask().synchronizePolicyTypes(ric, client)) //
228                 .collectList() //
229                 .flatMap(list -> Mono.just(ric)) //
230                 .doOnNext(notUsed -> ric.setState(RicState.AVAILABLE)) //
231                 .doOnError(t -> {
232                     logger.warn("Failed to synchronize types in new RIC: {}, reason: {}", ric.id(), t.getMessage());
233                     ric.setState(RicState.UNAVAILABLE); //
234                 }) //
235                 .onErrorResume(t -> Mono.just(ric));
236     }
237
238     public Mono<RicConfigUpdate.Type> handleUpdatedRicConfig(RicConfigUpdate updatedInfo) {
239         synchronized (this.rics) {
240             String ricId = updatedInfo.getRicConfig().ricId();
241             RicConfigUpdate.Type event = updatedInfo.getType();
242             if (event == RicConfigUpdate.Type.ADDED) {
243                 logger.debug("RIC added {}", ricId);
244
245                 return trySyncronizeSupportedTypes(new Ric(updatedInfo.getRicConfig())) //
246                         .flatMap(this::addRic) //
247                         .flatMap(this::notifyServicesRicAvailable) //
248                         .flatMap(notUsed -> Mono.just(event));
249             } else if (event == RicConfigUpdate.Type.REMOVED) {
250                 logger.debug("RIC removed {}", ricId);
251                 Ric ric = rics.remove(ricId);
252                 this.policies.removePoliciesForRic(ricId);
253                 removePoliciciesInRic(ric);
254             } else if (event == RicConfigUpdate.Type.CHANGED) {
255                 logger.debug("RIC config updated {}", ricId);
256                 Ric ric = this.rics.get(ricId);
257                 if (ric == null) {
258                     logger.error("An non existing RIC config is changed, should not happen (just for robustness)");
259                     addRic(new Ric(updatedInfo.getRicConfig())).block();
260                 } else {
261                     ric.setRicConfig(updatedInfo.getRicConfig());
262                 }
263             }
264             return Mono.just(event);
265         }
266     }
267
268     Mono<Ric> addRic(Ric ric) {
269         this.rics.put(ric);
270         if (this.appConfig.getVardataDirectory() != null) {
271             this.policies.restoreFromDatabase(ric, this.policyTypes);
272         }
273         logger.debug("Added RIC: {}", ric.id());
274
275         return Mono.just(ric);
276     }
277
278     private Mono<Ric> notifyServicesRicAvailable(Ric ric) {
279         if (ric.getState() == RicState.AVAILABLE) {
280             ServiceCallbacks callbacks = new ServiceCallbacks(this.restClientFactory);
281             return callbacks.notifyServicesRicAvailable(ric, services) //
282                     .collectList() //
283                     .flatMap(list -> Mono.just(ric));
284         } else {
285             return Mono.just(ric);
286         }
287     }
288
289     /**
290      * Reads the configuration from file.
291      */
292     Flux<JsonObject> loadConfigurationFromFile() {
293         Optional<JsonObject> readJson = configurationFile.readFile();
294         if (readJson.isPresent()) {
295             return Flux.just(readJson.get());
296         }
297         return Flux.empty();
298     }
299 }