Add all required and reasonable MDCs
[dcaegen2/collectors/hv-ves.git] / sources / hv-collector-core / src / main / kotlin / org / onap / dcae / collectors / veshv / impl / VesHvCollector.kt
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
21
22 import arrow.core.Either
23 import io.netty.buffer.ByteBuf
24 import org.onap.dcae.collectors.veshv.boundary.Collector
25 import org.onap.dcae.collectors.veshv.boundary.Metrics
26 import org.onap.dcae.collectors.veshv.boundary.Sink
27 import org.onap.dcae.collectors.veshv.domain.ByteData
28 import org.onap.dcae.collectors.veshv.domain.WireFrameMessage
29 import org.onap.dcae.collectors.veshv.impl.adapters.ClientContextLogging.handleReactiveStreamError
30 import org.onap.dcae.collectors.veshv.impl.wire.WireChunkDecoder
31 import org.onap.dcae.collectors.veshv.model.ClientContext
32 import org.onap.dcae.collectors.veshv.model.RoutedMessage
33 import org.onap.dcae.collectors.veshv.model.VesMessage
34 import org.onap.dcae.collectors.veshv.utils.logging.Logger
35 import org.onap.dcae.collectors.veshv.utils.logging.filterEmptyWithLog
36 import org.onap.dcae.collectors.veshv.utils.logging.filterFailedWithLog
37 import reactor.core.publisher.Flux
38 import reactor.core.publisher.Mono
39
40 /**
41  * @author Piotr Jaszczyk <piotr.jaszczyk@nokia.com>
42  * @since May 2018
43  */
44 internal class VesHvCollector(
45         private val clientContext: ClientContext,
46         private val wireChunkDecoder: WireChunkDecoder,
47         private val protobufDecoder: VesDecoder,
48         private val router: Router,
49         private val sink: Sink,
50         private val metrics: Metrics) : Collector {
51
52     override fun handleConnection(dataStream: Flux<ByteBuf>): Mono<Void> =
53             dataStream
54                     .transform { decodeWireFrame(it) }
55                     .transform(::filterInvalidWireFrame)
56                     .transform(::decodeProtobufPayload)
57                     .transform(::filterInvalidProtobufMessages)
58                     .transform(::routeMessage)
59                     .onErrorResume { logger.handleReactiveStreamError(clientContext, it) }
60                     .doFinally { releaseBuffersMemory() }
61                     .then()
62
63     private fun decodeWireFrame(flux: Flux<ByteBuf>): Flux<WireFrameMessage> = flux
64             .doOnNext { metrics.notifyBytesReceived(it.readableBytes()) }
65             .concatMap(wireChunkDecoder::decode)
66             .doOnNext { metrics.notifyMessageReceived(it.payloadSize) }
67
68     private fun filterInvalidWireFrame(flux: Flux<WireFrameMessage>): Flux<WireFrameMessage> = flux
69             .filterFailedWithLog(MessageValidator::validateFrameMessage)
70
71     private fun decodeProtobufPayload(flux: Flux<WireFrameMessage>): Flux<VesMessage> = flux
72             .map(WireFrameMessage::payload)
73             .flatMap(::decodePayload)
74
75     private fun decodePayload(rawPayload: ByteData): Flux<VesMessage> = protobufDecoder
76             .decode(rawPayload)
77             .filterFailedWithLog(logger, clientContext::fullMdc,
78                     { "Ves event header decoded successfully" },
79                     { "Failed to decode ves event header, reason: ${it.message}" })
80
81     private fun filterInvalidProtobufMessages(flux: Flux<VesMessage>): Flux<VesMessage> = flux
82             .filterFailedWithLog(MessageValidator::validateProtobufMessage)
83
84     private fun routeMessage(flux: Flux<VesMessage>): Flux<RoutedMessage> = flux
85             .flatMap(this::findRoute)
86             .compose(sink::send)
87             .doOnNext { metrics.notifyMessageSent(it.topic) }
88
89     private fun findRoute(msg: VesMessage) = router
90             .findDestination(msg)
91             .filterEmptyWithLog(logger, clientContext::fullMdc,
92                     { "Found route for message: ${it.topic}, partition: ${it.partition}" },
93                     { "Could not find route for message" })
94
95     private fun releaseBuffersMemory() = wireChunkDecoder.release()
96             .also { logger.debug { "Released buffer memory after handling message stream" } }
97
98     fun <T> Flux<T>.filterFailedWithLog(predicate: (T) -> Either<() -> String, () -> String>) =
99             filterFailedWithLog(logger, clientContext::fullMdc, predicate)
100
101     companion object {
102         private val logger = Logger(VesHvCollector::class)
103     }
104 }