4982c73281392c40d562c7dc5453d3cee100fc89
[dcaegen2/collectors/hv-ves.git] /
1 /*
2  * ============LICENSE_START=======================================================
3  * dcaegen2-collectors-veshv
4  * ================================================================================
5  * Copyright (C) 2018-2019 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.config.impl
21
22 import arrow.core.toOption
23 import com.google.gson.JsonObject
24 import org.onap.dcae.collectors.veshv.config.api.ConfigurationStateListener
25 import org.onap.dcae.collectors.veshv.config.api.model.CbsConfiguration
26 import org.onap.dcae.collectors.veshv.utils.logging.Logger
27 import org.onap.dcae.collectors.veshv.utils.logging.MappedDiagnosticContext
28 import org.onap.dcae.collectors.veshv.utils.logging.onErrorLog
29 import org.onap.dcae.collectors.veshv.utils.reader
30 import org.onap.dcaegen2.services.sdk.model.streams.StreamType.KAFKA
31 import org.onap.dcaegen2.services.sdk.model.streams.dmaap.KafkaSink
32 import org.onap.dcaegen2.services.sdk.rest.services.cbs.client.api.CbsClient
33 import org.onap.dcaegen2.services.sdk.rest.services.cbs.client.api.CbsRequests
34 import org.onap.dcaegen2.services.sdk.rest.services.cbs.client.api.streams.DataStreams
35 import org.onap.dcaegen2.services.sdk.rest.services.cbs.client.api.streams.StreamFromGsonParser
36 import org.onap.dcaegen2.services.sdk.rest.services.cbs.client.api.streams.StreamFromGsonParsers
37 import org.onap.dcaegen2.services.sdk.rest.services.cbs.client.api.streams.StreamPredicates.streamOfType
38 import org.onap.dcaegen2.services.sdk.rest.services.model.logging.RequestDiagnosticContext
39 import reactor.core.publisher.Flux
40 import reactor.core.publisher.Mono
41 import reactor.retry.Jitter
42 import reactor.retry.Retry
43
44 /**
45  * @author Jakub Dudycz <jakub.dudycz@nokia.com>
46  * @since May 2018
47  */
48 internal class CbsConfigurationProvider(private val cbsClientMono: Mono<CbsClient>,
49                                         private val cbsConfiguration: CbsConfiguration,
50                                         private val configParser: JsonConfigurationParser,
51                                         private val streamParser: StreamFromGsonParser<KafkaSink>,
52                                         private val configurationStateListener: ConfigurationStateListener,
53                                         private val mdc: MappedDiagnosticContext,
54                                         retrySpec: Retry<Any>
55
56 ) {
57     constructor(cbsClientMono: Mono<CbsClient>,
58                 cbsConfig: CbsConfiguration,
59                 configParser: JsonConfigurationParser,
60                 configurationStateListener: ConfigurationStateListener,
61                 mdc: MappedDiagnosticContext) :
62             this(
63                     cbsClientMono,
64                     cbsConfig,
65                     configParser,
66                     StreamFromGsonParsers.kafkaSinkParser(),
67                     configurationStateListener,
68                     mdc,
69                     Retry.any<Any>()
70                             .retryMax(MAX_RETRIES)
71                             .fixedBackoff(cbsConfig.requestInterval)
72                             .jitter(Jitter.random())
73             )
74
75     private val retry = retrySpec.doOnRetry {
76         logger.withWarn(mdc) {
77             log("Exception from configuration provider client, retrying subscription", it.exception())
78         }
79         configurationStateListener.retrying()
80     }
81
82     operator fun invoke(): Flux<PartialConfiguration> =
83             cbsClientMono
84                     .doOnNext { logger.info(mdc) { "CBS client successfully created" } }
85                     .onErrorLog(logger, mdc) { "Failed to retrieve CBS client" }
86                     .retryWhen(retry)
87                     .doFinally { logger.trace(mdc) { "CBS client subscription finished" } }
88                     .flatMapMany(::handleUpdates)
89
90     private fun handleUpdates(cbsClient: CbsClient) = cbsClient
91             .updates(CbsRequests.getConfiguration(RequestDiagnosticContext.create()),
92                     cbsConfiguration.firstRequestDelay,
93                     cbsConfiguration.requestInterval)
94             .doOnNext { logger.info(mdc) { "Received new configuration:\n$it" } }
95             .map(::parseConfiguration)
96             .doOnNext { logger.info(mdc) { "Successfully parsed configuration json to:\n$it" } }
97             .onErrorLog(logger, mdc) { "Error while creating configuration" }
98             .retryWhen(retry)
99
100     private fun parseConfiguration(json: JsonObject) =
101             configParser
102                     .parse(json.reader())
103                     .apply { streamPublishers = extractStreamDefinitions(json).toOption() }
104
105     private fun extractStreamDefinitions(configuration: JsonObject): List<KafkaSink> =
106             DataStreams.namedSinks(configuration)
107                     .filter(streamOfType(KAFKA))
108                     .map(streamParser::unsafeParse)
109                     .asIterable()
110                     .toList()
111
112     companion object {
113         private const val MAX_RETRIES = 5L
114         private val logger = Logger(CbsConfigurationProvider::class)
115     }
116 }