d08ad9e924f4af1e2c245e2d00a0b282a1414d06
[dcaegen2/collectors/hv-ves.git] /
1 /*
2  * ============LICENSE_START=======================================================
3  * dcaegen2-collectors-veshv
4  * ================================================================================
5  * Copyright (C) 2018 NOKIA
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 package org.onap.dcae.collectors.veshv.impl.adapters
21
22 import org.onap.dcae.collectors.veshv.boundary.ConfigurationProvider
23 import org.onap.dcae.collectors.veshv.healthcheck.api.HealthDescription
24 import org.onap.dcae.collectors.veshv.healthcheck.api.HealthState
25 import org.onap.dcae.collectors.veshv.model.CollectorConfiguration
26 import org.onap.dcae.collectors.veshv.model.ConfigurationProviderParams
27 import org.onap.dcae.collectors.veshv.utils.logging.Logger
28 import reactor.core.publisher.Flux
29 import reactor.core.publisher.Mono
30 import reactor.retry.Jitter
31 import reactor.retry.Retry
32 import java.io.StringReader
33 import java.time.Duration
34 import java.util.*
35 import java.util.concurrent.atomic.AtomicReference
36 import javax.json.Json
37 import javax.json.JsonObject
38
39
40 /**
41  * @author Jakub Dudycz <jakub.dudycz@nokia.com>
42  * @since May 2018
43  */
44 internal class ConsulConfigurationProvider(private val http: HttpAdapter,
45                                            private val url: String,
46                                            private val firstRequestDelay: Duration,
47                                            private val requestInterval: Duration,
48                                            private val healthState: HealthState,
49                                            retrySpec: Retry<Any>
50
51 ) : ConfigurationProvider {
52
53     private val lastConfigurationHash: AtomicReference<Int> = AtomicReference(0)
54     private val retry = retrySpec
55             .doOnRetry {
56                 logger.warn("Could not get fresh configuration", it.exception())
57                 healthState.changeState(HealthDescription.RETRYING_FOR_CONSUL_CONFIGURATION)
58             }
59
60     constructor(http: HttpAdapter,
61                 params: ConfigurationProviderParams) : this(
62             http,
63             params.configurationUrl,
64             params.firstRequestDelay,
65             params.requestInterval,
66             HealthState.INSTANCE,
67             Retry.any<Any>()
68                     .retryMax(MAX_RETRIES)
69                     .fixedBackoff(params.requestInterval.dividedBy(BACKOFF_INTERVAL_FACTOR))
70                     .jitter(Jitter.random())
71     )
72
73     override fun invoke(): Flux<CollectorConfiguration> =
74             Flux.interval(firstRequestDelay, requestInterval)
75                     .flatMap { askForConfig() }
76                     .map(::parseJsonResponse)
77                     .map(::extractEncodedConfiguration)
78                     .flatMap(::filterDifferentValues)
79                     .map(::decodeConfiguration)
80                     .map(::createCollectorConfiguration)
81                     .retryWhen(retry)
82
83     private fun askForConfig(): Mono<String> = http.get(url)
84
85     private fun parseJsonResponse(responseString: String): JsonObject =
86             Json.createReader(StringReader(responseString)).readArray().first().asJsonObject()
87
88     private fun extractEncodedConfiguration(response: JsonObject): String =
89             response.getString("Value")
90
91     private fun filterDifferentValues(base64Value: String): Mono<String> {
92         val newHash = hashOf(base64Value)
93         return if (newHash == lastConfigurationHash.get()) {
94             Mono.empty()
95         } else {
96             lastConfigurationHash.set(newHash)
97             Mono.just(base64Value)
98         }
99     }
100
101     private fun hashOf(str: String) = str.hashCode()
102
103     private fun decodeConfiguration(encodedConfiguration: String): JsonObject {
104         val decodedValue = String(Base64.getDecoder().decode(encodedConfiguration))
105         logger.info("Obtained new configuration from consul:\n$decodedValue")
106         return Json.createReader(StringReader(decodedValue)).readObject()
107     }
108
109     private fun createCollectorConfiguration(configuration: JsonObject): CollectorConfiguration {
110         val routing = configuration.getJsonArray("collector.routing")
111
112         return CollectorConfiguration(
113                 kafkaBootstrapServers = configuration.getString("dmaap.kafkaBootstrapServers"),
114                 routing = org.onap.dcae.collectors.veshv.model.routing {
115                     for (route in routing) {
116                         val routeObj = route.asJsonObject()
117                         defineRoute {
118                             fromDomain(routeObj.getString("fromDomain"))
119                             toTopic(routeObj.getString("toTopic"))
120                             withFixedPartitioning()
121                         }
122                     }
123                 }.build()
124         )
125     }
126
127     companion object {
128         private const val MAX_RETRIES = 5
129         private const val BACKOFF_INTERVAL_FACTOR = 30L
130         private val logger = Logger(ConsulConfigurationProvider::class)
131     }
132 }
133