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.exceptions.ServiceException;
56 import org.oransc.policyagent.repository.Policies;
57 import org.oransc.policyagent.repository.PolicyTypes;
58 import org.oransc.policyagent.repository.Ric;
59 import org.oransc.policyagent.repository.Rics;
60 import org.oransc.policyagent.repository.Services;
61 import org.slf4j.Logger;
62 import org.slf4j.LoggerFactory;
63 import org.springframework.beans.factory.annotation.Autowired;
64 import org.springframework.beans.factory.annotation.Value;
65 import org.springframework.stereotype.Component;
67 import reactor.core.Disposable;
68 import reactor.core.publisher.Flux;
69 import reactor.core.publisher.Mono;
72 * Regularly refreshes the configuration from Consul or from a local
76 public class RefreshConfigTask {
78 private static final Logger logger = LoggerFactory.getLogger(RefreshConfigTask.class);
80 @Value("#{systemEnvironment}")
81 public Properties systemEnvironment;
83 final ApplicationConfig appConfig;
84 @Getter(AccessLevel.PROTECTED)
85 private Disposable refreshTask = null;
86 private boolean isConsulUsed = false;
88 private final Rics rics;
89 private final A1ClientFactory a1ClientFactory;
90 private final Policies policies;
91 private final Services services;
92 private final PolicyTypes policyTypes;
93 private static final Duration FILE_CONFIG_REFRESH_INTERVAL = Duration.ofMinutes(1);
94 private static final Duration CONSUL_CONFIG_REFRESH_INTERVAL = Duration.ofMinutes(1);
97 public RefreshConfigTask(ApplicationConfig appConfig, Rics rics, Policies policies, Services services,
98 PolicyTypes policyTypes, A1ClientFactory a1ClientFactory) {
99 this.appConfig = appConfig;
101 this.policies = policies;
102 this.services = services;
103 this.policyTypes = policyTypes;
104 this.a1ClientFactory = a1ClientFactory;
107 public void start() {
108 logger.debug("Starting refreshConfigTask");
110 refreshTask = createRefreshTask() //
111 .subscribe(notUsed -> logger.debug("Refreshed configuration data"),
112 throwable -> logger.error("Configuration refresh terminated due to exception {}", throwable.toString()),
113 () -> logger.error("Configuration refresh terminated"));
117 if (refreshTask != null) {
118 refreshTask.dispose();
122 Flux<RicConfigUpdate.Type> createRefreshTask() {
123 Flux<JsonObject> loadFromFile = Flux.interval(Duration.ZERO, FILE_CONFIG_REFRESH_INTERVAL) //
124 .filter(notUsed -> !this.isConsulUsed) //
125 .flatMap(notUsed -> loadConfigurationFromFile()) //
126 .onErrorResume(this::ignoreErrorFlux) //
127 .doOnNext(json -> logger.debug("loadFromFile succeeded")) //
128 .doOnTerminate(() -> logger.error("loadFromFile Terminate"));
130 Flux<JsonObject> loadFromConsul = Flux.interval(Duration.ZERO, CONSUL_CONFIG_REFRESH_INTERVAL) //
131 .flatMap(i -> getEnvironment(systemEnvironment)) //
132 .flatMap(this::createCbsClient) //
133 .flatMap(this::getFromCbs) //
134 .onErrorResume(this::ignoreErrorMono) //
135 .doOnNext(json -> logger.debug("loadFromConsul succeeded")) //
136 .doOnNext(json -> this.isConsulUsed = true) //
137 .doOnTerminate(() -> logger.error("loadFromConsul Terminated"));
139 return Flux.merge(loadFromFile, loadFromConsul) //
140 .flatMap(this::parseConfiguration) //
141 .flatMap(this::updateConfig) //
142 .doOnNext(this::handleUpdatedRicConfig) //
143 .flatMap(configUpdate -> Flux.just(configUpdate.getType())) //
144 .doOnTerminate(() -> logger.error("Configuration refresh task is terminated"));
147 Mono<EnvProperties> getEnvironment(Properties systemEnvironment) {
148 return EnvironmentProcessor.readEnvironmentVariables(systemEnvironment) //
149 .onErrorResume(t -> Mono.empty());
152 Mono<CbsClient> createCbsClient(EnvProperties env) {
153 return CbsClientFactory.createCbsClient(env) //
154 .onErrorResume(this::ignoreErrorMono);
157 private Mono<JsonObject> getFromCbs(CbsClient cbsClient) {
158 final CbsRequest getConfigRequest = CbsRequests.getAll(RequestDiagnosticContext.create());
160 return cbsClient.get(getConfigRequest) //
161 .onErrorResume(this::ignoreErrorMono);
162 } catch (Exception e) {
163 return ignoreErrorMono(e);
167 private <R> Flux<R> ignoreErrorFlux(Throwable throwable) {
168 String errMsg = throwable.toString();
169 logger.warn("Could not refresh application configuration. {}", errMsg);
173 private <R> Mono<R> ignoreErrorMono(Throwable throwable) {
174 String errMsg = throwable.toString();
175 logger.warn("Could not refresh application configuration. {}", errMsg);
179 private Mono<ApplicationConfigParser.ConfigParserResult> parseConfiguration(JsonObject jsonObject) {
181 ApplicationConfigParser parser = new ApplicationConfigParser();
182 return Mono.just(parser.parse(jsonObject));
183 } catch (Exception e) {
184 String str = e.toString();
185 logger.error("Could not parse configuration {}", str);
190 private Flux<RicConfigUpdate> updateConfig(ApplicationConfigParser.ConfigParserResult config) {
191 return this.appConfig.setConfiguration(config);
194 boolean fileExists(String filepath) {
195 return (filepath != null && (new File(filepath).exists()));
198 private void handleUpdatedRicConfig(RicConfigUpdate updatedInfo) {
199 synchronized (this.rics) {
200 String ricName = updatedInfo.getRicConfig().name();
201 RicConfigUpdate.Type event = updatedInfo.getType();
202 if (event == RicConfigUpdate.Type.ADDED) {
203 addRic(updatedInfo.getRicConfig());
204 } else if (event == RicConfigUpdate.Type.REMOVED) {
205 rics.remove(ricName);
206 this.policies.removePoliciesForRic(ricName);
207 } else if (event == RicConfigUpdate.Type.CHANGED) {
208 Ric ric = this.rics.get(ricName);
210 // Should not happen,just for robustness
211 addRic(updatedInfo.getRicConfig());
213 ric.setRicConfig(updatedInfo.getRicConfig());
219 private void addRic(RicConfig config) {
220 Ric ric = new Ric(config);
222 runRicSynchronization(ric);
225 void runRicSynchronization(Ric ric) {
226 RicSynchronizationTask synchronizationTask =
227 new RicSynchronizationTask(a1ClientFactory, policyTypes, policies, services);
228 synchronizationTask.run(ric);
232 * Reads the configuration from file.
234 Flux<JsonObject> loadConfigurationFromFile() {
235 String filepath = appConfig.getLocalConfigurationFilePath();
236 if (!fileExists(filepath)) {
240 GsonBuilder gsonBuilder = new GsonBuilder();
241 ServiceLoader.load(TypeAdapterFactory.class).forEach(gsonBuilder::registerTypeAdapterFactory);
243 try (InputStream inputStream = createInputStream(filepath)) {
244 JsonObject rootObject = getJsonElement(inputStream).getAsJsonObject();
245 ApplicationConfigParser appParser = new ApplicationConfigParser();
246 appParser.parse(rootObject);
247 logger.debug("Local configuration file loaded: {}", filepath);
248 return Flux.just(rootObject);
249 } catch (IOException | ServiceException e) {
250 logger.error("Local configuration file not loaded: {}, {}", filepath, e.getMessage());
255 JsonElement getJsonElement(InputStream inputStream) {
256 return JsonParser.parseReader(new InputStreamReader(inputStream));
259 InputStream createInputStream(@NotNull String filepath) throws IOException {
260 return new BufferedInputStream(new FileInputStream(filepath));