651ba5ed391831f53384e19e8851b3c2b01cf3b6
[ccsdk/oran.git] /
1 /*-
2  * ========================LICENSE_START=================================
3  * ONAP : ccsdk oran
4  * ======================================================================
5  * Copyright (C) 2019-2020 Nordix Foundation. All rights reserved.
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.onap.ccsdk.oran.a1policymanagementservice.tasks;
22
23 import com.google.gson.JsonObject;
24
25 import java.time.Duration;
26 import java.util.Optional;
27 import java.util.Properties;
28
29 import lombok.AccessLevel;
30 import lombok.Getter;
31
32 import org.onap.ccsdk.oran.a1policymanagementservice.clients.A1ClientFactory;
33 import org.onap.ccsdk.oran.a1policymanagementservice.clients.AsyncRestClientFactory;
34 import org.onap.ccsdk.oran.a1policymanagementservice.configuration.ApplicationConfig;
35 import org.onap.ccsdk.oran.a1policymanagementservice.configuration.ApplicationConfig.RicConfigUpdate;
36 import org.onap.ccsdk.oran.a1policymanagementservice.configuration.ApplicationConfigParser;
37 import org.onap.ccsdk.oran.a1policymanagementservice.configuration.ConfigurationFile;
38 import org.onap.ccsdk.oran.a1policymanagementservice.controllers.ServiceCallbacks;
39 import org.onap.ccsdk.oran.a1policymanagementservice.repository.Policies;
40 import org.onap.ccsdk.oran.a1policymanagementservice.repository.PolicyTypes;
41 import org.onap.ccsdk.oran.a1policymanagementservice.repository.Ric;
42 import org.onap.ccsdk.oran.a1policymanagementservice.repository.Ric.RicState;
43 import org.onap.ccsdk.oran.a1policymanagementservice.repository.Rics;
44 import org.onap.ccsdk.oran.a1policymanagementservice.repository.Services;
45 import org.slf4j.Logger;
46 import org.slf4j.LoggerFactory;
47 import org.springframework.beans.factory.annotation.Autowired;
48 import org.springframework.beans.factory.annotation.Value;
49 import org.springframework.stereotype.Component;
50
51 import reactor.core.Disposable;
52 import reactor.core.publisher.Flux;
53 import reactor.core.publisher.Mono;
54 import reactor.util.annotation.Nullable;
55
56 /**
57  * Regularly refreshes the component configuration from a configuration file.
58  */
59 @Component
60 @SuppressWarnings("squid:S2629") // Invoke method(s) only conditionally
61 public class RefreshConfigTask {
62
63     private static final Logger logger = LoggerFactory.getLogger(RefreshConfigTask.class);
64
65     @Value("#{systemEnvironment}")
66     public Properties systemEnvironment;
67
68     /**
69      * The time between refreshes of the configuration. Not final so tests can
70      * modify it.
71      */
72     private static Duration configRefreshInterval = Duration.ofMinutes(1);
73
74     final ConfigurationFile configurationFile;
75     final ApplicationConfig appConfig;
76
77     @Getter(AccessLevel.PROTECTED)
78     private Disposable refreshTask = null;
79
80     private final Rics rics;
81     private final A1ClientFactory a1ClientFactory;
82     private final Policies policies;
83     private final Services services;
84     private final PolicyTypes policyTypes;
85     private final AsyncRestClientFactory restClientFactory;
86
87     private long fileLastModified = 0;
88
89     @Autowired
90     public RefreshConfigTask(ConfigurationFile configurationFile, ApplicationConfig appConfig, Rics rics,
91             Policies policies, Services services, PolicyTypes policyTypes, A1ClientFactory a1ClientFactory) {
92         this.configurationFile = configurationFile;
93         this.appConfig = appConfig;
94         this.rics = rics;
95         this.policies = policies;
96         this.services = services;
97         this.policyTypes = policyTypes;
98         this.a1ClientFactory = a1ClientFactory;
99         this.restClientFactory = new AsyncRestClientFactory(appConfig.getWebClientConfig());
100     }
101
102     public void start() {
103         logger.debug("Starting refreshConfigTask");
104         stop();
105         refreshTask = createRefreshTask() //
106                 .subscribe(
107                         notUsed -> logger.debug("Refreshed configuration data"), throwable -> logger
108                                 .error("Configuration refresh terminated due to exception {}", throwable.toString()),
109                         () -> logger.error("Configuration refresh terminated"));
110     }
111
112     public void stop() {
113         if (refreshTask != null) {
114             refreshTask.dispose();
115         }
116     }
117
118     Flux<RicConfigUpdate.Type> createRefreshTask() {
119         Flux<JsonObject> loadFromFile = regularInterval() //
120                 .flatMap(notUsed -> loadConfigurationFromFile()) //
121                 .onErrorResume(this::ignoreErrorFlux) //
122                 .doOnNext(json -> logger.debug("loadFromFile succeeded")) //
123                 .doOnTerminate(() -> logger.error("loadFromFile Terminate"));
124
125         final int CONCURRENCY = 50; // Number of RIC synched in paralell
126
127         return loadFromFile //
128                 .flatMap(this::parseConfiguration) //
129                 .flatMap(this::updateConfig, CONCURRENCY) //
130                 .flatMap(this::handleUpdatedRicConfig) //
131                 .doOnTerminate(() -> logger.error("Configuration refresh task is terminated"));
132     }
133
134     private Flux<Long> regularInterval() {
135         return Flux.interval(Duration.ZERO, configRefreshInterval) //
136                 .onBackpressureDrop() //
137                 .limitRate(1); // Limit so that only one event is emitted at a time
138     }
139
140     private <R> Flux<R> ignoreErrorFlux(Throwable throwable) {
141         String errMsg = throwable.toString();
142         logger.warn("Could not refresh application configuration. {}", errMsg);
143         return Flux.empty();
144     }
145
146     private Mono<ApplicationConfigParser.ConfigParserResult> parseConfiguration(JsonObject jsonObject) {
147         try {
148             ApplicationConfigParser parser = new ApplicationConfigParser(this.appConfig);
149             return Mono.just(parser.parse(jsonObject));
150         } catch (Exception e) {
151             String str = e.toString();
152             logger.error("Could not parse configuration {}", str);
153             return Mono.empty();
154         }
155     }
156
157     private Flux<RicConfigUpdate> updateConfig(ApplicationConfigParser.ConfigParserResult config) {
158         return this.appConfig.setConfiguration(config);
159     }
160
161     private void removePoliciciesInRic(@Nullable Ric ric) {
162         if (ric != null) {
163             synchronizationTask().run(ric);
164         }
165     }
166
167     private RicSynchronizationTask synchronizationTask() {
168         return new RicSynchronizationTask(a1ClientFactory, policyTypes, policies, services, restClientFactory, rics);
169     }
170
171     /**
172      * for an added RIC after a restart it is nesessary to get the suypported policy
173      * types from the RIC unless a full synchronization is wanted.
174      * 
175      * @param ric the ric to get supprted types from
176      * @return the same ric
177      */
178     private Mono<Ric> trySyncronizeSupportedTypes(Ric ric) {
179         logger.debug("Synchronizing policy types for new RIC: {}", ric.id());
180         // Synchronize the policy types
181         ric.setState(RicState.SYNCHRONIZING);
182         return this.a1ClientFactory.createA1Client(ric) //
183                 .flatMapMany(client -> synchronizationTask().synchronizePolicyTypes(ric, client)) //
184                 .collectList() //
185                 .map(list -> ric) //
186                 .doOnNext(notUsed -> ric.setState(RicState.AVAILABLE)) //
187                 .doOnError(t -> {
188                     logger.warn("Failed to synchronize types in new RIC: {}, reason: {}", ric.id(), t.getMessage());
189                     ric.setState(RicState.UNAVAILABLE); //
190                 }) //
191                 .onErrorResume(t -> Mono.just(ric));
192     }
193
194     public Mono<RicConfigUpdate.Type> handleUpdatedRicConfig(RicConfigUpdate updatedInfo) {
195         synchronized (this.rics) {
196             String ricId = updatedInfo.getRicConfig().ricId();
197             RicConfigUpdate.Type event = updatedInfo.getType();
198             if (event == RicConfigUpdate.Type.ADDED) {
199                 logger.debug("RIC added {}", ricId);
200
201                 return trySyncronizeSupportedTypes(new Ric(updatedInfo.getRicConfig())) //
202                         .doOnNext(this::addRic) //
203                         .flatMap(this::notifyServicesRicAvailable) //
204                         .flatMap(notUsed -> Mono.just(event));
205             } else if (event == RicConfigUpdate.Type.REMOVED) {
206                 logger.debug("RIC removed {}", ricId);
207                 Ric ric = rics.remove(ricId);
208                 this.policies.removePoliciesForRic(ricId);
209                 removePoliciciesInRic(ric);
210             } else if (event == RicConfigUpdate.Type.CHANGED) {
211                 logger.debug("RIC config updated {}", ricId);
212                 Ric ric = this.rics.get(ricId);
213                 if (ric == null) {
214                     logger.error("An non existing RIC config is changed, should not happen (just for robustness)");
215                     addRic(new Ric(updatedInfo.getRicConfig()));
216                 } else {
217                     ric.setRicConfig(updatedInfo.getRicConfig());
218                 }
219             }
220             return Mono.just(event);
221         }
222     }
223
224     void addRic(Ric ric) {
225         this.rics.put(ric);
226         if (this.appConfig.getVardataDirectory() != null) {
227             this.policies.restoreFromDatabase(ric, this.policyTypes);
228         }
229         logger.debug("Added RIC: {}", ric.id());
230     }
231
232     private Mono<Ric> notifyServicesRicAvailable(Ric ric) {
233         if (ric.getState() == RicState.AVAILABLE) {
234             ServiceCallbacks callbacks = new ServiceCallbacks(this.restClientFactory);
235             return callbacks.notifyServicesRicAvailable(ric, services) //
236                     .collectList() //
237                     .map(list -> ric);
238         } else {
239             return Mono.just(ric);
240         }
241     }
242
243     /**
244      * Reads the configuration from file.
245      */
246     Flux<JsonObject> loadConfigurationFromFile() {
247         if (configurationFile.getLastModified() == fileLastModified) {
248             return Flux.empty();
249         }
250         fileLastModified = configurationFile.getLastModified();
251         Optional<JsonObject> readJson = configurationFile.readFile();
252         if (readJson.isPresent()) {
253             return Flux.just(readJson.get());
254         }
255         return Flux.empty();
256     }
257 }