Merge "Added STD sim 2.0.0 tests"
[nonrtric.git] / policy-agent / src / main / java / org / oransc / policyagent / tasks / RefreshConfigTask.java
index 7cfe486..b99a230 100644 (file)
@@ -24,7 +24,6 @@ import com.google.gson.GsonBuilder;
 import com.google.gson.JsonElement;
 import com.google.gson.JsonObject;
 import com.google.gson.JsonParser;
-import com.google.gson.JsonSyntaxException;
 import com.google.gson.TypeAdapterFactory;
 
 import java.io.BufferedInputStream;
@@ -53,7 +52,6 @@ import org.oransc.policyagent.configuration.ApplicationConfig;
 import org.oransc.policyagent.configuration.ApplicationConfig.RicConfigUpdate;
 import org.oransc.policyagent.configuration.ApplicationConfigParser;
 import org.oransc.policyagent.configuration.RicConfig;
-import org.oransc.policyagent.exceptions.ServiceException;
 import org.oransc.policyagent.repository.Policies;
 import org.oransc.policyagent.repository.PolicyTypes;
 import org.oransc.policyagent.repository.Ric;
@@ -70,8 +68,7 @@ import reactor.core.publisher.Flux;
 import reactor.core.publisher.Mono;
 
 /**
- * Regularly refreshes the configuration from Consul or from a local
- * configuration file.
+ * Regularly refreshes the configuration from Consul or from a local configuration file.
  */
 @Component
 public class RefreshConfigTask {
@@ -81,6 +78,11 @@ public class RefreshConfigTask {
     @Value("#{systemEnvironment}")
     public Properties systemEnvironment;
 
+    /**
+     * The time between refreshes of the configuration.
+     */
+    static final Duration CONFIG_REFRESH_INTERVAL = Duration.ofMinutes(1);
+
     final ApplicationConfig appConfig;
     @Getter(AccessLevel.PROTECTED)
     private Disposable refreshTask = null;
@@ -91,8 +93,6 @@ public class RefreshConfigTask {
     private final Policies policies;
     private final Services services;
     private final PolicyTypes policyTypes;
-    private static final Duration FILE_CONFIG_REFRESH_INTERVAL = Duration.ofMinutes(1);
-    private static final Duration CONSUL_CONFIG_REFRESH_INTERVAL = Duration.ofMinutes(1);
 
     @Autowired
     public RefreshConfigTask(ApplicationConfig appConfig, Rics rics, Policies policies, Services services,
@@ -109,9 +109,8 @@ public class RefreshConfigTask {
         logger.debug("Starting refreshConfigTask");
         stop();
         refreshTask = createRefreshTask() //
-            .subscribe(
-                notUsed -> logger.debug("Refreshed configuration data"), throwable -> logger
-                    .error("Configuration refresh terminated due to exception {}", throwable.getMessage()),
+            .subscribe(notUsed -> logger.debug("Refreshed configuration data"),
+                throwable -> logger.error("Configuration refresh terminated due to exception {}", throwable.toString()),
                 () -> logger.error("Configuration refresh terminated"));
     }
 
@@ -122,18 +121,18 @@ public class RefreshConfigTask {
     }
 
     Flux<RicConfigUpdate.Type> createRefreshTask() {
-        Flux<JsonObject> loadFromFile = Flux.interval(Duration.ZERO, FILE_CONFIG_REFRESH_INTERVAL) //
-            .filter(notUsed -> configFileExists()) //
+        Flux<JsonObject> loadFromFile = Flux.interval(Duration.ZERO, CONFIG_REFRESH_INTERVAL) //
             .filter(notUsed -> !this.isConsulUsed) //
             .flatMap(notUsed -> loadConfigurationFromFile()) //
-            .onErrorResume(this::ignoreError) //
+            .onErrorResume(this::ignoreErrorFlux) //
             .doOnNext(json -> logger.debug("loadFromFile succeeded")) //
             .doOnTerminate(() -> logger.error("loadFromFile Terminate"));
 
-        Flux<JsonObject> loadFromConsul = getEnvironment(systemEnvironment) //
+        Flux<JsonObject> loadFromConsul = Flux.interval(Duration.ZERO, CONFIG_REFRESH_INTERVAL) //
+            .flatMap(i -> getEnvironment(systemEnvironment)) //
             .flatMap(this::createCbsClient) //
-            .flatMapMany(this::periodicConfigurationUpdates) //
-            .onErrorResume(this::ignoreError) //
+            .flatMap(this::getFromCbs) //
+            .onErrorResume(this::ignoreErrorMono) //
             .doOnNext(json -> logger.debug("loadFromConsul succeeded")) //
             .doOnNext(json -> this.isConsulUsed = true) //
             .doOnTerminate(() -> logger.error("loadFromConsul Terminated"));
@@ -147,20 +146,32 @@ public class RefreshConfigTask {
     }
 
     Mono<EnvProperties> getEnvironment(Properties systemEnvironment) {
-        return EnvironmentProcessor.readEnvironmentVariables(systemEnvironment);
+        return EnvironmentProcessor.readEnvironmentVariables(systemEnvironment) //
+            .onErrorResume(t -> Mono.empty());
     }
 
     Mono<CbsClient> createCbsClient(EnvProperties env) {
-        return CbsClientFactory.createCbsClient(env);
+        return CbsClientFactory.createCbsClient(env) //
+            .onErrorResume(this::ignoreErrorMono);
     }
 
-    private Flux<JsonObject> periodicConfigurationUpdates(CbsClient cbsClient) {
-        final Duration initialDelay = Duration.ZERO;
-        final CbsRequest getConfigRequest = CbsRequests.getAll(RequestDiagnosticContext.create());
-        return cbsClient.updates(getConfigRequest, initialDelay, CONSUL_CONFIG_REFRESH_INTERVAL);
+    private Mono<JsonObject> getFromCbs(CbsClient cbsClient) {
+        try {
+            final CbsRequest getConfigRequest = CbsRequests.getAll(RequestDiagnosticContext.create());
+            return cbsClient.get(getConfigRequest) //
+                .onErrorResume(this::ignoreErrorMono);
+        } catch (Exception e) {
+            return ignoreErrorMono(e);
+        }
     }
 
-    private <R> Mono<R> ignoreError(Throwable throwable) {
+    private <R> Flux<R> ignoreErrorFlux(Throwable throwable) {
+        String errMsg = throwable.toString();
+        logger.warn("Could not refresh application configuration. {}", errMsg);
+        return Flux.empty();
+    }
+
+    private <R> Mono<R> ignoreErrorMono(Throwable throwable) {
         String errMsg = throwable.toString();
         logger.warn("Could not refresh application configuration. {}", errMsg);
         return Mono.empty();
@@ -170,9 +181,10 @@ public class RefreshConfigTask {
         try {
             ApplicationConfigParser parser = new ApplicationConfigParser();
             return Mono.just(parser.parse(jsonObject));
-        } catch (ServiceException e) {
-            logger.error("Could not parse configuration {}", e.toString(), e);
-            return Mono.error(e);
+        } catch (Exception e) {
+            String str = e.toString();
+            logger.error("Could not parse configuration {}", str);
+            return Mono.empty();
         }
     }
 
@@ -180,8 +192,7 @@ public class RefreshConfigTask {
         return this.appConfig.setConfiguration(config);
     }
 
-    boolean configFileExists() {
-        String filepath = appConfig.getLocalConfigurationFilePath();
+    boolean fileExists(String filepath) {
         return (filepath != null && (new File(filepath).exists()));
     }
 
@@ -223,6 +234,10 @@ public class RefreshConfigTask {
      */
     Flux<JsonObject> loadConfigurationFromFile() {
         String filepath = appConfig.getLocalConfigurationFilePath();
+        if (!fileExists(filepath)) {
+            return Flux.empty();
+        }
+
         GsonBuilder gsonBuilder = new GsonBuilder();
         ServiceLoader.load(TypeAdapterFactory.class).forEach(gsonBuilder::registerTypeAdapterFactory);
 
@@ -232,8 +247,8 @@ public class RefreshConfigTask {
             appParser.parse(rootObject);
             logger.debug("Local configuration file loaded: {}", filepath);
             return Flux.just(rootObject);
-        } catch (JsonSyntaxException | ServiceException | IOException e) {
-            logger.debug("Local configuration file not loaded: {}", filepath, e);
+        } catch (Exception e) {
+            logger.error("Local configuration file not loaded: {}, {}", filepath, e.getMessage());
             return Flux.empty();
         }
     }