185693c0f883617d0b81800b940b254da1e4de67
[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.impl.adapters
21
22 import com.google.gson.JsonObject
23 import org.onap.dcae.collectors.veshv.boundary.ConfigurationProvider
24 import org.onap.dcae.collectors.veshv.config.api.model.CbsConfiguration
25 import org.onap.dcae.collectors.veshv.config.api.model.Route
26 import org.onap.dcae.collectors.veshv.config.api.model.Routing
27 import org.onap.dcae.collectors.veshv.healthcheck.api.HealthDescription
28 import org.onap.dcae.collectors.veshv.healthcheck.api.HealthState
29 import org.onap.dcae.collectors.veshv.model.ServiceContext
30 import org.onap.dcae.collectors.veshv.utils.logging.Logger
31 import org.onap.dcae.collectors.veshv.utils.logging.onErrorLog
32 import org.onap.dcaegen2.services.sdk.model.streams.StreamType.KAFKA
33 import org.onap.dcaegen2.services.sdk.model.streams.dmaap.KafkaSink
34 import org.onap.dcaegen2.services.sdk.rest.services.cbs.client.api.CbsClient
35 import org.onap.dcaegen2.services.sdk.rest.services.cbs.client.api.CbsRequests
36 import org.onap.dcaegen2.services.sdk.rest.services.cbs.client.api.streams.DataStreams
37 import org.onap.dcaegen2.services.sdk.rest.services.cbs.client.api.streams.StreamFromGsonParser
38 import org.onap.dcaegen2.services.sdk.rest.services.cbs.client.api.streams.StreamFromGsonParsers
39 import org.onap.dcaegen2.services.sdk.rest.services.cbs.client.api.streams.StreamPredicates.streamOfType
40 import org.onap.dcaegen2.services.sdk.rest.services.model.logging.RequestDiagnosticContext
41 import reactor.core.publisher.Flux
42 import reactor.core.publisher.Mono
43 import reactor.retry.Jitter
44 import reactor.retry.Retry
45 import java.time.Duration
46
47 /**
48  * @author Jakub Dudycz <jakub.dudycz@nokia.com>
49  * @since May 2018
50  */
51 internal class ConfigurationProviderImpl(private val cbsClientMono: Mono<CbsClient>,
52                                          private val firstRequestDelay: Duration,
53                                          private val requestInterval: Duration,
54                                          private val healthState: HealthState,
55                                          private val streamParser: StreamFromGsonParser<KafkaSink>,
56                                          retrySpec: Retry<Any>
57
58 ) : ConfigurationProvider {
59     constructor(cbsClientMono: Mono<CbsClient>, params: CbsConfiguration) : this(
60             cbsClientMono,
61             params.firstRequestDelay,
62             params.requestInterval,
63             HealthState.INSTANCE,
64             StreamFromGsonParsers.kafkaSinkParser(),
65             Retry.any<Any>()
66                     .retryMax(MAX_RETRIES)
67                     .fixedBackoff(params.requestInterval)
68                     .jitter(Jitter.random())
69     )
70
71     private val retry = retrySpec.doOnRetry {
72         logger.withWarn(ServiceContext::mdc) {
73             log("Exception from configuration provider client, retrying subscription", it.exception())
74         }
75         healthState.changeState(HealthDescription.RETRYING_FOR_DYNAMIC_CONFIGURATION)
76     }
77
78     override fun invoke(): Flux<Routing> =
79             cbsClientMono
80                     .doOnNext { logger.info(ServiceContext::mdc) { "CBS client successfully created" } }
81                     .onErrorLog(logger, ServiceContext::mdc) { "Failed to retrieve CBS client" }
82                     .retryWhen(retry)
83                     .doFinally { logger.trace(ServiceContext::mdc) { "CBS client subscription finished" } }
84                     .flatMapMany(::handleUpdates)
85
86     private fun handleUpdates(cbsClient: CbsClient) = cbsClient
87             .updates(CbsRequests.getConfiguration(RequestDiagnosticContext.create()),
88                     firstRequestDelay,
89                     requestInterval)
90             .doOnNext { logger.info(ServiceContext::mdc) { "Received new configuration:\n$it" } }
91             .map(::createRoutingDescription)
92             .onErrorLog(logger, ServiceContext::mdc) { "Error while creating configuration" }
93             .retryWhen(retry)
94
95     private fun createRoutingDescription(configuration: JsonObject): Routing = try {
96         DataStreams.namedSinks(configuration)
97                 .filter(streamOfType(KAFKA))
98                 .map(streamParser::unsafeParse)
99                 .map { Route(it.name(), it) }
100                 .asIterable()
101                 .toList()
102     } catch (e: NullPointerException) {
103         throw ParsingException("Failed to parse configuration", e)
104     }
105
106     companion object {
107         private const val MAX_RETRIES = 5L
108         private val logger = Logger(ConfigurationProviderImpl::class)
109     }
110 }