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