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 com.google.gson.GsonBuilder;
24 import com.google.gson.JsonElement;
25 import com.google.gson.JsonObject;
26 import com.google.gson.JsonParser;
27 import com.google.gson.TypeAdapterFactory;
29 import java.io.BufferedInputStream;
31 import java.io.FileInputStream;
32 import java.io.IOException;
33 import java.io.InputStream;
34 import java.io.InputStreamReader;
35 import java.time.Duration;
36 import java.util.Properties;
37 import java.util.ServiceLoader;
39 import javax.validation.constraints.NotNull;
41 import lombok.AccessLevel;
44 import org.onap.dcaegen2.services.sdk.rest.services.cbs.client.api.CbsClient;
45 import org.onap.dcaegen2.services.sdk.rest.services.cbs.client.api.CbsClientFactory;
46 import org.onap.dcaegen2.services.sdk.rest.services.cbs.client.api.CbsRequests;
47 import org.onap.dcaegen2.services.sdk.rest.services.cbs.client.model.CbsRequest;
48 import org.onap.dcaegen2.services.sdk.rest.services.cbs.client.model.EnvProperties;
49 import org.onap.dcaegen2.services.sdk.rest.services.model.logging.RequestDiagnosticContext;
50 import org.oransc.policyagent.clients.A1ClientFactory;
51 import org.oransc.policyagent.configuration.ApplicationConfig;
52 import org.oransc.policyagent.configuration.ApplicationConfig.RicConfigUpdate;
53 import org.oransc.policyagent.configuration.ApplicationConfigParser;
54 import org.oransc.policyagent.configuration.RicConfig;
55 import org.oransc.policyagent.repository.Policies;
56 import org.oransc.policyagent.repository.PolicyTypes;
57 import org.oransc.policyagent.repository.Ric;
58 import org.oransc.policyagent.repository.Rics;
59 import org.oransc.policyagent.repository.Services;
60 import org.slf4j.Logger;
61 import org.slf4j.LoggerFactory;
62 import org.springframework.beans.factory.annotation.Autowired;
63 import org.springframework.beans.factory.annotation.Value;
64 import org.springframework.stereotype.Component;
66 import reactor.core.Disposable;
67 import reactor.core.publisher.Flux;
68 import reactor.core.publisher.Mono;
71 * Regularly refreshes the configuration from Consul or from a local configuration file.
74 public class RefreshConfigTask {
76 private static final Logger logger = LoggerFactory.getLogger(RefreshConfigTask.class);
78 @Value("#{systemEnvironment}")
79 public Properties systemEnvironment;
82 * The time between refreshes of the configuration.
84 static final Duration CONFIG_REFRESH_INTERVAL = Duration.ofMinutes(1);
86 final ApplicationConfig appConfig;
87 @Getter(AccessLevel.PROTECTED)
88 private Disposable refreshTask = null;
89 private boolean isConsulUsed = false;
91 private final Rics rics;
92 private final A1ClientFactory a1ClientFactory;
93 private final Policies policies;
94 private final Services services;
95 private final PolicyTypes policyTypes;
98 public RefreshConfigTask(ApplicationConfig appConfig, Rics rics, Policies policies, Services services,
99 PolicyTypes policyTypes, A1ClientFactory a1ClientFactory) {
100 this.appConfig = appConfig;
102 this.policies = policies;
103 this.services = services;
104 this.policyTypes = policyTypes;
105 this.a1ClientFactory = a1ClientFactory;
108 public void start() {
109 logger.debug("Starting refreshConfigTask");
111 refreshTask = createRefreshTask() //
112 .subscribe(notUsed -> logger.debug("Refreshed configuration data"),
113 throwable -> logger.error("Configuration refresh terminated due to exception {}", throwable.toString()),
114 () -> logger.error("Configuration refresh terminated"));
118 if (refreshTask != null) {
119 refreshTask.dispose();
123 Flux<RicConfigUpdate.Type> createRefreshTask() {
124 Flux<JsonObject> loadFromFile = Flux.interval(Duration.ZERO, CONFIG_REFRESH_INTERVAL) //
125 .filter(notUsed -> !this.isConsulUsed) //
126 .flatMap(notUsed -> loadConfigurationFromFile()) //
127 .onErrorResume(this::ignoreErrorFlux) //
128 .doOnNext(json -> logger.debug("loadFromFile succeeded")) //
129 .doOnTerminate(() -> logger.error("loadFromFile Terminate"));
131 Flux<JsonObject> loadFromConsul = Flux.interval(Duration.ZERO, CONFIG_REFRESH_INTERVAL) //
132 .flatMap(i -> getEnvironment(systemEnvironment)) //
133 .flatMap(this::createCbsClient) //
134 .flatMap(this::getFromCbs) //
135 .onErrorResume(this::ignoreErrorMono) //
136 .doOnNext(json -> logger.debug("loadFromConsul succeeded")) //
137 .doOnNext(json -> this.isConsulUsed = true) //
138 .doOnTerminate(() -> logger.error("loadFromConsul Terminated"));
140 return Flux.merge(loadFromFile, loadFromConsul) //
141 .flatMap(this::parseConfiguration) //
142 .flatMap(this::updateConfig) //
143 .doOnNext(this::handleUpdatedRicConfig) //
144 .flatMap(configUpdate -> Flux.just(configUpdate.getType())) //
145 .doOnTerminate(() -> logger.error("Configuration refresh task is terminated"));
148 Mono<EnvProperties> getEnvironment(Properties systemEnvironment) {
149 return EnvironmentProcessor.readEnvironmentVariables(systemEnvironment) //
150 .onErrorResume(t -> Mono.empty());
153 Mono<CbsClient> createCbsClient(EnvProperties env) {
154 return CbsClientFactory.createCbsClient(env) //
155 .onErrorResume(this::ignoreErrorMono);
158 private Mono<JsonObject> getFromCbs(CbsClient cbsClient) {
160 final CbsRequest getConfigRequest = CbsRequests.getAll(RequestDiagnosticContext.create());
161 return cbsClient.get(getConfigRequest) //
162 .onErrorResume(this::ignoreErrorMono);
163 } catch (Exception e) {
164 return ignoreErrorMono(e);
168 private <R> Flux<R> ignoreErrorFlux(Throwable throwable) {
169 String errMsg = throwable.toString();
170 logger.warn("Could not refresh application configuration. {}", errMsg);
174 private <R> Mono<R> ignoreErrorMono(Throwable throwable) {
175 String errMsg = throwable.toString();
176 logger.warn("Could not refresh application configuration. {}", errMsg);
180 private Mono<ApplicationConfigParser.ConfigParserResult> parseConfiguration(JsonObject jsonObject) {
182 ApplicationConfigParser parser = new ApplicationConfigParser();
183 return Mono.just(parser.parse(jsonObject));
184 } catch (Exception e) {
185 String str = e.toString();
186 logger.error("Could not parse configuration {}", str);
191 private Flux<RicConfigUpdate> updateConfig(ApplicationConfigParser.ConfigParserResult config) {
192 return this.appConfig.setConfiguration(config);
195 boolean fileExists(String filepath) {
196 return (filepath != null && (new File(filepath).exists()));
199 private void handleUpdatedRicConfig(RicConfigUpdate updatedInfo) {
200 synchronized (this.rics) {
201 String ricName = updatedInfo.getRicConfig().name();
202 RicConfigUpdate.Type event = updatedInfo.getType();
203 if (event == RicConfigUpdate.Type.ADDED) {
204 addRic(updatedInfo.getRicConfig());
205 } else if (event == RicConfigUpdate.Type.REMOVED) {
206 rics.remove(ricName);
207 this.policies.removePoliciesForRic(ricName);
208 } else if (event == RicConfigUpdate.Type.CHANGED) {
209 Ric ric = this.rics.get(ricName);
211 // Should not happen,just for robustness
212 addRic(updatedInfo.getRicConfig());
214 ric.setRicConfig(updatedInfo.getRicConfig());
220 private void addRic(RicConfig config) {
221 Ric ric = new Ric(config);
223 runRicSynchronization(ric);
226 void runRicSynchronization(Ric ric) {
227 RicSynchronizationTask synchronizationTask =
228 new RicSynchronizationTask(a1ClientFactory, policyTypes, policies, services);
229 synchronizationTask.run(ric);
233 * Reads the configuration from file.
235 Flux<JsonObject> loadConfigurationFromFile() {
236 String filepath = appConfig.getLocalConfigurationFilePath();
237 if (!fileExists(filepath)) {
241 GsonBuilder gsonBuilder = new GsonBuilder();
242 ServiceLoader.load(TypeAdapterFactory.class).forEach(gsonBuilder::registerTypeAdapterFactory);
244 try (InputStream inputStream = createInputStream(filepath)) {
245 JsonObject rootObject = getJsonElement(inputStream).getAsJsonObject();
246 ApplicationConfigParser appParser = new ApplicationConfigParser();
247 appParser.parse(rootObject);
248 logger.debug("Local configuration file loaded: {}", filepath);
249 return Flux.just(rootObject);
250 } catch (Exception e) {
251 logger.error("Local configuration file not loaded: {}, {}", filepath, e.getMessage());
256 JsonElement getJsonElement(InputStream inputStream) {
257 return JsonParser.parseReader(new InputStreamReader(inputStream));
260 InputStream createInputStream(@NotNull String filepath) throws IOException {
261 return new BufferedInputStream(new FileInputStream(filepath));