Move RefreshConfigTask under tasks
[nonrtric.git] / policy-agent / src / main / java / org / oransc / policyagent / tasks / RefreshConfigTask.java
1 /*-
2  * ========================LICENSE_START=================================
3  * O-RAN-SC
4  * %%
5  * Copyright (C) 2019 Nordix Foundation
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.oransc.policyagent.tasks;
22
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.JsonSyntaxException;
28 import com.google.gson.TypeAdapterFactory;
29
30 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;
38
39 import javax.validation.constraints.NotNull;
40
41 import org.onap.dcaegen2.services.sdk.rest.services.cbs.client.api.CbsClient;
42 import org.onap.dcaegen2.services.sdk.rest.services.cbs.client.api.CbsClientFactory;
43 import org.onap.dcaegen2.services.sdk.rest.services.cbs.client.api.CbsRequests;
44 import org.onap.dcaegen2.services.sdk.rest.services.cbs.client.model.CbsRequest;
45 import org.onap.dcaegen2.services.sdk.rest.services.cbs.client.model.EnvProperties;
46 import org.onap.dcaegen2.services.sdk.rest.services.model.logging.RequestDiagnosticContext;
47 import org.oransc.policyagent.configuration.ApplicationConfig;
48 import org.oransc.policyagent.configuration.ApplicationConfigParser;
49 import org.oransc.policyagent.exceptions.ServiceException;
50 import org.slf4j.Logger;
51 import org.slf4j.LoggerFactory;
52 import org.springframework.beans.factory.annotation.Autowired;
53 import org.springframework.beans.factory.annotation.Value;
54 import org.springframework.stereotype.Component;
55
56 import reactor.core.Disposable;
57 import reactor.core.publisher.Flux;
58 import reactor.core.publisher.Mono;
59
60 /**
61  * Regularly refreshes the configuration from Consul.
62  */
63 @Component
64 public class RefreshConfigTask {
65
66     private static final Logger logger = LoggerFactory.getLogger(RefreshConfigTask.class);
67
68     @Value("#{systemEnvironment}")
69     public Properties systemEnvironment;
70
71     private final ApplicationConfig appConfig;
72     private Disposable refreshTask = null;
73
74     @Autowired
75     public RefreshConfigTask(ApplicationConfig appConfig) {
76         this.appConfig = appConfig;
77     }
78
79     public void start() {
80         logger.debug("Starting refreshConfigTask");
81         stop();
82         loadConfigurationFromFile();
83         refreshTask = createRefreshTask() //
84             .subscribe(notUsed -> logger.info("Refreshed configuration data"),
85                 throwable -> logger.error("Configuration refresh terminated due to exception", throwable),
86                 () -> logger.error("Configuration refresh terminated"));
87     }
88
89     public void stop() {
90         if (refreshTask != null) {
91             refreshTask.dispose();
92             refreshTask = null;
93         }
94     }
95
96     Flux<ApplicationConfig> createRefreshTask() {
97         return getEnvironment(systemEnvironment) //
98             .flatMap(this::createCbsClient) //
99             .flatMapMany(this::periodicConfigurationUpdates) //
100             .map(this::parseRicConfigurationfromConsul) //
101             .onErrorResume(this::onErrorResume);
102     }
103
104     Mono<EnvProperties> getEnvironment(Properties systemEnvironment) {
105         return EnvironmentProcessor.readEnvironmentVariables(systemEnvironment);
106     }
107
108     Mono<CbsClient> createCbsClient(EnvProperties env) {
109         return CbsClientFactory.createCbsClient(env);
110     }
111
112     private Flux<JsonObject> periodicConfigurationUpdates(CbsClient cbsClient) {
113         final Duration initialDelay = Duration.ZERO;
114         final Duration refreshPeriod = Duration.ofMinutes(1);
115         final CbsRequest getConfigRequest = CbsRequests.getAll(RequestDiagnosticContext.create());
116         return cbsClient.updates(getConfigRequest, initialDelay, refreshPeriod);
117     }
118
119     private <R> Mono<R> onErrorResume(Throwable trowable) {
120         logger.error("Could not refresh application configuration {}", trowable.toString());
121         return Mono.empty();
122     }
123
124     private ApplicationConfig parseRicConfigurationfromConsul(JsonObject jsonObject) {
125         try {
126             ApplicationConfigParser parser = new ApplicationConfigParser();
127             parser.parse(jsonObject);
128             this.appConfig.setConfiguration(parser.getRicConfigs());
129         } catch (ServiceException e) {
130             logger.error("Could not parse configuration {}", e.toString(), e);
131         }
132         return this.appConfig;
133     }
134
135     /**
136      * Reads the configuration from file.
137      */
138     public void loadConfigurationFromFile() {
139         String filepath = appConfig.getLocalConfigurationFilePath();
140         if (filepath == null) {
141             logger.debug("No localconfiguration file used");
142             return;
143         }
144         GsonBuilder gsonBuilder = new GsonBuilder();
145         ServiceLoader.load(TypeAdapterFactory.class).forEach(gsonBuilder::registerTypeAdapterFactory);
146
147         try (InputStream inputStream = createInputStream(filepath)) {
148             JsonParser parser = new JsonParser();
149             JsonObject rootObject = getJsonElement(parser, inputStream).getAsJsonObject();
150             if (rootObject == null) {
151                 throw new JsonSyntaxException("Root is not a json object");
152             }
153             ApplicationConfigParser appParser = new ApplicationConfigParser();
154             appParser.parse(rootObject);
155             appConfig.setConfiguration(appParser.getRicConfigs());
156             logger.info("Local configuration file loaded: {}", filepath);
157         } catch (JsonSyntaxException | ServiceException | IOException e) {
158             logger.trace("Local configuration file not loaded: {}", filepath, e);
159         }
160     }
161
162     JsonElement getJsonElement(JsonParser parser, InputStream inputStream) {
163         return parser.parse(new InputStreamReader(inputStream));
164     }
165
166     InputStream createInputStream(@NotNull String filepath) throws IOException {
167         return new BufferedInputStream(new FileInputStream(filepath));
168     }
169 }