04471c88629d656ec41f834628004e0ea83c83eb
[nonrtric.git] / policy-agent / src / main / java / org / oransc / policyagent / configuration / ApplicationConfig.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.configuration;
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.Optional;
37 import java.util.Properties;
38 import java.util.ServiceLoader;
39 import java.util.Vector;
40
41 import javax.validation.constraints.NotEmpty;
42 import javax.validation.constraints.NotNull;
43
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.exceptions.ServiceException;
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.boot.context.properties.ConfigurationProperties;
56 import org.springframework.boot.context.properties.EnableConfigurationProperties;
57 import reactor.core.Disposable;
58 import reactor.core.publisher.Flux;
59 import reactor.core.publisher.Mono;
60
61 @EnableConfigurationProperties
62 @ConfigurationProperties("app")
63 public class ApplicationConfig {
64     private static final Logger logger = LoggerFactory.getLogger(ApplicationConfig.class);
65
66     @Value("#{systemEnvironment}")
67     Properties systemEnvironment;
68
69     private Disposable refreshConfigTask = null;
70
71     @NotEmpty
72     private String filepath;
73
74     private Vector<RicConfig> ricConfigs;
75
76     @Autowired
77     public ApplicationConfig() {
78     }
79
80     public synchronized void setFilepath(String filepath) {
81         this.filepath = filepath;
82     }
83
84     public Vector<RicConfig> getRicConfigs() {
85         return this.ricConfigs;
86     }
87
88     public Optional<RicConfig> lookupRicConfigForManagedElement(String managedElementId) {
89         for (RicConfig ricConfig : getRicConfigs()) {
90             if (ricConfig.managedElementIds().contains(managedElementId)) {
91                 return Optional.of(ricConfig);
92             }
93         }
94         return Optional.empty();
95     }
96
97     public RicConfig getRic(String ricName) throws ServiceException {
98         for (RicConfig ricConfig : getRicConfigs()) {
99             if (ricConfig.name().equals(ricName)) {
100                 return ricConfig;
101             }
102         }
103         throw new ServiceException("Could not find ric: " + ricName);
104     }
105
106     public void initialize() {
107         stop();
108         loadConfigurationFromFile(this.filepath);
109
110         refreshConfigTask = createRefreshTask() //
111                 .subscribe(e -> logger.info("Refreshed configuration data"),
112                         throwable -> logger.error("Configuration refresh terminated due to exception", throwable),
113                         () -> logger.error("Configuration refresh terminated"));
114     }
115
116     Mono<EnvProperties> getEnvironment(Properties systemEnvironment) {
117         return EnvironmentProcessor.readEnvironmentVariables(systemEnvironment);
118     }
119
120     Flux<ApplicationConfig> createRefreshTask() {
121         return getEnvironment(systemEnvironment) //
122                 .flatMap(this::createCbsClient) //
123                 .flatMapMany(this::periodicConfigurationUpdates) //
124                 .map(this::parseRicConfigurationfromConsul) //
125                 .onErrorResume(this::onErrorResume);
126     }
127
128     Mono<CbsClient> createCbsClient(EnvProperties env) {
129         return CbsClientFactory.createCbsClient(env);
130     }
131
132     private Flux<JsonObject> periodicConfigurationUpdates(CbsClient cbsClient) {
133         final Duration initialDelay = Duration.ZERO;
134         final Duration refreshPeriod = Duration.ofMinutes(1);
135         final CbsRequest getConfigRequest = CbsRequests.getAll(RequestDiagnosticContext.create());
136         return cbsClient.updates(getConfigRequest, initialDelay, refreshPeriod);
137     }
138
139     private <R> Mono<R> onErrorResume(Throwable trowable) {
140         logger.error("Could not refresh application configuration {}", trowable.toString());
141         return Mono.empty();
142     }
143
144     private ApplicationConfig parseRicConfigurationfromConsul(JsonObject jsonObject) {
145         try {
146             ApplicationConfigParser parser = new ApplicationConfigParser();
147             parser.parse(jsonObject);
148             setConfiguration(parser.getRicConfigs());
149
150         } catch (ServiceException e) {
151             logger.error("Could not parse configuration {}", e.toString(), e);
152         }
153         return this;
154     }
155
156     private synchronized void setConfiguration(@NotNull  Vector<RicConfig> ricConfigs) {
157         this.ricConfigs = ricConfigs;
158     }
159
160     public void stop() {
161         if (refreshConfigTask != null) {
162             refreshConfigTask.dispose();
163             refreshConfigTask = null;
164         }
165     }
166
167     /**
168      * Reads the configuration from file.
169      */
170     protected void loadConfigurationFromFile(String filepath) {
171         GsonBuilder gsonBuilder = new GsonBuilder();
172         ServiceLoader.load(TypeAdapterFactory.class).forEach(gsonBuilder::registerTypeAdapterFactory);
173
174         try (InputStream inputStream = createInputStream(filepath)) {
175             JsonParser parser = new JsonParser();
176             JsonObject rootObject = getJsonElement(parser, inputStream).getAsJsonObject();
177             if (rootObject == null) {
178                 throw new JsonSyntaxException("Root is not a json object");
179             }
180             ApplicationConfigParser appParser = new ApplicationConfigParser();
181             appParser.parse(rootObject);
182             this.ricConfigs = appParser.getRicConfigs();
183             logger.info("Local configuration file loaded: {}", filepath);
184         } catch (JsonSyntaxException | ServiceException | IOException e) {
185             logger.trace("Local configuration file not loaded: {}", filepath, e);
186         }
187     }
188
189     JsonElement getJsonElement(JsonParser parser, InputStream inputStream) {
190         return parser.parse(new InputStreamReader(inputStream));
191     }
192
193     InputStream createInputStream(@NotNull String filepath) throws IOException {
194         return new BufferedInputStream(new FileInputStream(filepath));
195     }
196
197 }