7fd54a7c3dbe0fb1ee0feed84e45271d8300d51b
[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     private long fileLastModified = 0;
98
99     @Autowired
100     public RefreshConfigTask(ConfigurationFile configurationFile, ApplicationConfig appConfig, Rics rics,
101             Policies policies, Services services, PolicyTypes policyTypes, A1ClientFactory a1ClientFactory) {
102         this.configurationFile = configurationFile;
103         this.appConfig = appConfig;
104         this.rics = rics;
105         this.policies = policies;
106         this.services = services;
107         this.policyTypes = policyTypes;
108         this.a1ClientFactory = a1ClientFactory;
109         this.restClientFactory = new AsyncRestClientFactory(appConfig.getWebClientConfig());
110     }
111
112     public void start() {
113         logger.debug("Starting refreshConfigTask");
114         stop();
115         refreshTask = createRefreshTask() //
116                 .subscribe(
117                         notUsed -> logger.debug("Refreshed configuration data"), throwable -> logger
118                                 .error("Configuration refresh terminated due to exception {}", throwable.toString()),
119                         () -> logger.error("Configuration refresh terminated"));
120     }
121
122     public void stop() {
123         if (refreshTask != null) {
124             refreshTask.dispose();
125         }
126     }
127
128     Flux<RicConfigUpdate.Type> createRefreshTask() {
129         Flux<JsonObject> loadFromFile = regularInterval() //
130                 .filter(notUsed -> !this.isConsulUsed) //
131                 .flatMap(notUsed -> loadConfigurationFromFile()) //
132                 .onErrorResume(this::ignoreErrorFlux) //
133                 .doOnNext(json -> logger.debug("loadFromFile succeeded")) //
134                 .doOnTerminate(() -> logger.error("loadFromFile Terminate"));
135
136         Flux<JsonObject> loadFromConsul = regularInterval() //
137                 .flatMap(i -> getEnvironment(systemEnvironment)) //
138                 .flatMap(this::createCbsClient) //
139                 .flatMap(this::getFromCbs) //
140                 .onErrorResume(this::ignoreErrorMono) //
141                 .doOnNext(json -> logger.debug("loadFromConsul succeeded")) //
142                 .doOnNext(json -> this.isConsulUsed = true) //
143                 .doOnTerminate(() -> logger.error("loadFromConsul Terminated"));
144
145         final int CONCURRENCY = 50; // Number of RIC synched in paralell
146
147         return Flux.merge(loadFromFile, loadFromConsul) //
148                 .flatMap(this::parseConfiguration) //
149                 .flatMap(this::updateConfig, CONCURRENCY) //
150                 .flatMap(this::handleUpdatedRicConfig) //
151                 .doOnTerminate(() -> logger.error("Configuration refresh task is terminated"));
152     }
153
154     private Flux<Long> regularInterval() {
155         return Flux.interval(Duration.ZERO, configRefreshInterval) //
156                 .onBackpressureDrop() //
157                 .limitRate(1); // Limit so that only one event is emitted at a time
158     }
159
160     Mono<EnvProperties> getEnvironment(Properties systemEnvironment) {
161         return EnvironmentProcessor.readEnvironmentVariables(systemEnvironment) //
162                 .onErrorResume(t -> Mono.empty());
163     }
164
165     Mono<CbsClient> createCbsClient(EnvProperties env) {
166         return CbsClientFactory.createCbsClient(env) //
167                 .onErrorResume(this::ignoreErrorMono);
168     }
169
170     private Mono<JsonObject> getFromCbs(CbsClient cbsClient) {
171         try {
172             final CbsRequest getConfigRequest = CbsRequests.getAll(RequestDiagnosticContext.create());
173             return cbsClient.get(getConfigRequest) //
174                     .onErrorResume(this::ignoreErrorMono);
175         } catch (Exception e) {
176             return ignoreErrorMono(e);
177         }
178     }
179
180     private <R> Flux<R> ignoreErrorFlux(Throwable throwable) {
181         String errMsg = throwable.toString();
182         logger.warn("Could not refresh application configuration. {}", errMsg);
183         return Flux.empty();
184     }
185
186     private <R> Mono<R> ignoreErrorMono(Throwable throwable) {
187         String errMsg = throwable.toString();
188         logger.warn("Could not refresh application configuration. {}", errMsg);
189         return Mono.empty();
190     }
191
192     private Mono<ApplicationConfigParser.ConfigParserResult> parseConfiguration(JsonObject jsonObject) {
193         try {
194             ApplicationConfigParser parser = new ApplicationConfigParser(this.appConfig);
195             return Mono.just(parser.parse(jsonObject));
196         } catch (Exception e) {
197             String str = e.toString();
198             logger.error("Could not parse configuration {}", str);
199             return Mono.empty();
200         }
201     }
202
203     private Flux<RicConfigUpdate> updateConfig(ApplicationConfigParser.ConfigParserResult config) {
204         return this.appConfig.setConfiguration(config);
205     }
206
207     private void removePoliciciesInRic(@Nullable Ric ric) {
208         if (ric != null) {
209             synchronizationTask().run(ric);
210         }
211     }
212
213     private RicSynchronizationTask synchronizationTask() {
214         return new RicSynchronizationTask(a1ClientFactory, policyTypes, policies, services, restClientFactory, rics);
215     }
216
217     /**
218      * for an added RIC after a restart it is nesessary to get the suypported policy
219      * types from the RIC unless a full synchronization is wanted.
220      * 
221      * @param ric the ric to get supprted types from
222      * @return the same ric
223      */
224     private Mono<Ric> trySyncronizeSupportedTypes(Ric ric) {
225         logger.debug("Synchronizing policy types for new RIC: {}", ric.id());
226         // Synchronize the policy types
227         ric.setState(RicState.SYNCHRONIZING);
228         return this.a1ClientFactory.createA1Client(ric) //
229                 .flatMapMany(client -> synchronizationTask().synchronizePolicyTypes(ric, client)) //
230                 .collectList() //
231                 .map(list -> ric) //
232                 .doOnNext(notUsed -> ric.setState(RicState.AVAILABLE)) //
233                 .doOnError(t -> {
234                     logger.warn("Failed to synchronize types in new RIC: {}, reason: {}", ric.id(), t.getMessage());
235                     ric.setState(RicState.UNAVAILABLE); //
236                 }) //
237                 .onErrorResume(t -> Mono.just(ric));
238     }
239
240     public Mono<RicConfigUpdate.Type> handleUpdatedRicConfig(RicConfigUpdate updatedInfo) {
241         synchronized (this.rics) {
242             String ricId = updatedInfo.getRicConfig().ricId();
243             RicConfigUpdate.Type event = updatedInfo.getType();
244             if (event == RicConfigUpdate.Type.ADDED) {
245                 logger.debug("RIC added {}", ricId);
246
247                 return trySyncronizeSupportedTypes(new Ric(updatedInfo.getRicConfig())) //
248                         .doOnNext(this::addRic) //
249                         .flatMap(this::notifyServicesRicAvailable) //
250                         .flatMap(notUsed -> Mono.just(event));
251             } else if (event == RicConfigUpdate.Type.REMOVED) {
252                 logger.debug("RIC removed {}", ricId);
253                 Ric ric = rics.remove(ricId);
254                 this.policies.removePoliciesForRic(ricId);
255                 removePoliciciesInRic(ric);
256             } else if (event == RicConfigUpdate.Type.CHANGED) {
257                 logger.debug("RIC config updated {}", ricId);
258                 Ric ric = this.rics.get(ricId);
259                 if (ric == null) {
260                     logger.error("An non existing RIC config is changed, should not happen (just for robustness)");
261                     addRic(new Ric(updatedInfo.getRicConfig()));
262                 } else {
263                     ric.setRicConfig(updatedInfo.getRicConfig());
264                 }
265             }
266             return Mono.just(event);
267         }
268     }
269
270     void addRic(Ric ric) {
271         this.rics.put(ric);
272         if (this.appConfig.getVardataDirectory() != null) {
273             this.policies.restoreFromDatabase(ric, this.policyTypes);
274         }
275         logger.debug("Added RIC: {}", ric.id());
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                     .map(list -> ric);
284         } else {
285             return Mono.just(ric);
286         }
287     }
288
289     /**
290      * Reads the configuration from file.
291      */
292     Flux<JsonObject> loadConfigurationFromFile() {
293         if (configurationFile.getLastModified() == fileLastModified) {
294             return Flux.empty();
295         }
296         fileLastModified = configurationFile.getLastModified();
297         Optional<JsonObject> readJson = configurationFile.readFile();
298         if (readJson.isPresent()) {
299             return Flux.just(readJson.get());
300         }
301         return Flux.empty();
302     }
303 }