717da092067af95071b3295ec542c6efe07845d6
[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.model.ServiceContext
28 import org.onap.dcae.collectors.veshv.model.routing
29 import org.onap.dcae.collectors.veshv.utils.logging.Logger
30 import org.onap.dcae.collectors.veshv.utils.logging.Marker
31 import reactor.core.publisher.Flux
32 import reactor.core.publisher.Mono
33 import reactor.retry.Jitter
34 import reactor.retry.Retry
35 import java.io.StringReader
36 import java.security.MessageDigest
37 import java.time.Duration
38 import java.util.*
39 import java.util.concurrent.atomic.AtomicReference
40 import javax.json.Json
41 import javax.json.JsonObject
42
43
44 /**
45  * @author Jakub Dudycz <jakub.dudycz@nokia.com>
46  * @since May 2018
47  */
48 internal class ConsulConfigurationProvider(private val http: HttpAdapter,
49                                            private val url: String,
50                                            private val firstRequestDelay: Duration,
51                                            private val requestInterval: Duration,
52                                            private val healthState: HealthState,
53                                            retrySpec: Retry<Any>
54
55 ) : ConfigurationProvider {
56     private val lastConfigurationHash: AtomicReference<ByteArray> = AtomicReference(byteArrayOf())
57     private val retry = retrySpec
58             .doOnRetry {
59                 logger.withWarn(ServiceContext::mdc) { log("Could not get fresh configuration", it.exception()) }
60                 healthState.changeState(HealthDescription.RETRYING_FOR_CONSUL_CONFIGURATION)
61             }
62
63     constructor(http: HttpAdapter,
64                 params: ConfigurationProviderParams) : this(
65             http,
66             params.configurationUrl,
67             params.firstRequestDelay,
68             params.requestInterval,
69             HealthState.INSTANCE,
70             Retry.any<Any>()
71                     .retryMax(MAX_RETRIES)
72                     .fixedBackoff(params.requestInterval.dividedBy(BACKOFF_INTERVAL_FACTOR))
73                     .jitter(Jitter.random())
74     )
75
76     override fun invoke(): Flux<CollectorConfiguration> =
77             Flux.interval(firstRequestDelay, requestInterval)
78                     .concatMap { askForConfig() }
79                     .flatMap(::filterDifferentValues)
80                     .map(::parseJsonResponse)
81                     .map(::createCollectorConfiguration)
82                     .retryWhen(retry)
83
84     private fun askForConfig(): Mono<BodyWithInvocationId> = Mono.defer {
85         val invocationId = UUID.randomUUID()
86         http.get(url, invocationId).map { BodyWithInvocationId(it, invocationId) }
87     }
88
89     private fun filterDifferentValues(configuration: BodyWithInvocationId) =
90             configuration.body.let { configurationString ->
91                 configurationString.sha256().let { newHash ->
92                     if (newHash contentEquals lastConfigurationHash.get()) {
93                         logger.trace(ServiceContext::mdc, Marker.Invoke(configuration.invocationId)) {
94                             "No change detected in consul configuration"
95                         }
96                         Mono.empty()
97                     } else {
98                         logger.info(ServiceContext::mdc, Marker.Invoke(configuration.invocationId)) {
99                             "Obtained new configuration from consul:\n${configurationString}"
100                         }
101                         lastConfigurationHash.set(newHash)
102                         Mono.just(configurationString)
103                     }
104                 }
105             }
106
107     private fun parseJsonResponse(responseString: String): JsonObject =
108             Json.createReader(StringReader(responseString)).readObject()
109
110     private fun createCollectorConfiguration(configuration: JsonObject): CollectorConfiguration {
111         val routingArray = configuration.getJsonArray("collector.routing")
112
113         return CollectorConfiguration(
114                 routing {
115                     for (route in routingArray) {
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 = 5L
129         private const val BACKOFF_INTERVAL_FACTOR = 30L
130         private val logger = Logger(ConsulConfigurationProvider::class)
131
132         private fun String.sha256() =
133                 MessageDigest
134                         .getInstance("SHA-256")
135                         .digest(toByteArray())
136
137     }
138
139     private data class BodyWithInvocationId(val body: String, val invocationId: UUID)
140 }