dc45e354545d7ee76f40a5c5b6536b46904d12cf
[ccsdk/cds.git] / ms / blueprintsprocessor / modules / commons / rest-lib / src / main / kotlin / org / onap / ccsdk / cds / blueprintsprocessor / rest / service / RestLoggerService.kt
1 /*
2  * Copyright © 2018-2019 AT&T Intellectual Property.
3  * Modifications Copyright © 2020 Bell Canada.
4  *
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at
8  *
9  *     http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  */
17
18 package org.onap.ccsdk.cds.blueprintsprocessor.rest.service
19
20 import kotlinx.coroutines.AbstractCoroutine
21 import kotlinx.coroutines.CoroutineScope
22 import kotlinx.coroutines.CoroutineStart
23 import kotlinx.coroutines.GlobalScope
24 import kotlinx.coroutines.InternalCoroutinesApi
25 import kotlinx.coroutines.coroutineScope
26 import kotlinx.coroutines.handleCoroutineException
27 import kotlinx.coroutines.newCoroutineContext
28 import kotlinx.coroutines.reactor.ReactorContext
29 import kotlinx.coroutines.reactor.asCoroutineContext
30 import kotlinx.coroutines.withContext
31 import org.apache.http.message.BasicHeader
32 import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants
33 import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants.ONAP_INVOCATION_ID
34 import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants.ONAP_ORIGINATOR_ID
35 import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants.ONAP_PARTNER_NAME
36 import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants.ONAP_REQUEST_ID
37 import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants.ONAP_SUBREQUEST_ID
38 import org.onap.ccsdk.cds.controllerblueprints.core.MDCContext
39 import org.onap.ccsdk.cds.controllerblueprints.core.defaultToEmpty
40 import org.onap.ccsdk.cds.controllerblueprints.core.defaultToUUID
41 import org.onap.ccsdk.cds.controllerblueprints.core.logger
42 import org.slf4j.MDC
43 import org.springframework.http.server.reactive.ServerHttpRequest
44 import org.springframework.http.server.reactive.ServerHttpResponse
45 import reactor.core.Disposable
46 import reactor.core.publisher.Mono
47 import reactor.core.publisher.MonoSink
48 import java.net.InetAddress
49 import java.time.ZoneOffset
50 import java.time.ZonedDateTime
51 import java.time.format.DateTimeFormatter
52 import java.util.UUID
53 import kotlin.coroutines.CoroutineContext
54 import kotlin.coroutines.EmptyCoroutineContext
55
56 class RestLoggerService {
57     private val log = logger(RestLoggerService::class)
58
59     companion object {
60         /** Used before invoking any REST outbound request, Inbound Invocation ID is used as request Id
61          * for outbound Request, If invocation Id is missing then default Request Id will be generated.
62          */
63         fun httpInvoking(headers: Array<BasicHeader>) {
64             headers.plusElement(BasicHeader(ONAP_REQUEST_ID, MDC.get("InvocationID").defaultToUUID()))
65             headers.plusElement(BasicHeader(ONAP_INVOCATION_ID, UUID.randomUUID().toString()))
66             headers.plusElement(BasicHeader(ONAP_PARTNER_NAME, BluePrintConstants.APP_NAME))
67         }
68     }
69
70     fun entering(request: ServerHttpRequest) {
71         val localhost = InetAddress.getLocalHost()
72         val headers = request.headers
73         val requestID = headers.getFirst(ONAP_REQUEST_ID).defaultToUUID()
74         val subrequestID = headers.getFirst(ONAP_SUBREQUEST_ID).defaultToEmpty()
75         val originatorID = headers.getFirst(ONAP_ORIGINATOR_ID).defaultToEmpty()
76         val invocationID = headers.getFirst(ONAP_INVOCATION_ID).defaultToUUID()
77         val partnerName = headers.getFirst(ONAP_PARTNER_NAME).defaultToEmpty()
78         MDC.put("InvokeTimestamp", ZonedDateTime.now(ZoneOffset.UTC).format(DateTimeFormatter.ISO_INSTANT))
79         MDC.put("RequestID", requestID)
80         MDC.put("SubRequestID", subrequestID)
81         MDC.put("OriginatorID", originatorID)
82         MDC.put("InvocationID", invocationID)
83         MDC.put("PartnerName", partnerName)
84         MDC.put("ClientIPAddress", request.remoteAddress?.address?.hostAddress.defaultToEmpty())
85         MDC.put("ServerFQDN", localhost.hostName.defaultToEmpty())
86         if (MDC.get("ServiceName") == null || MDC.get("ServiceName").equals("", ignoreCase = true)) {
87             MDC.put("ServiceName", request.uri.path)
88         }
89     }
90
91     fun exiting(request: ServerHttpRequest, response: ServerHttpResponse) {
92         try {
93             val reqHeaders = request.headers
94             val resHeaders = response.headers
95             resHeaders[ONAP_REQUEST_ID] = MDC.get("RequestID")
96             resHeaders[ONAP_SUBREQUEST_ID] = MDC.get("SubRequestID")
97             resHeaders[ONAP_ORIGINATOR_ID] = MDC.get("OriginatorID")
98             resHeaders[ONAP_INVOCATION_ID] = MDC.get("InvocationID")
99             resHeaders[ONAP_PARTNER_NAME] = BluePrintConstants.APP_NAME
100         } catch (e: Exception) {
101             log.warn("couldn't set response headers", e)
102         } finally {
103             MDC.clear()
104         }
105     }
106 }
107
108 /** Used in Rest controller API methods to populate MDC context to nested coroutines from reactor web filter context. */
109 suspend fun <T> mdcWebCoroutineScope(
110     block: suspend CoroutineScope.() -> T
111 ) = coroutineScope {
112     val reactorContext = this.coroutineContext[ReactorContext]
113     /** Populate MDC context only if present in Reactor Context */
114     val newContext = if (reactorContext != null &&
115         !reactorContext.context.isEmpty &&
116         reactorContext.context.hasKey(MDCContext)
117     ) {
118         val mdcContext = reactorContext.context.get<MDCContext>(MDCContext)
119         if (mdcContext != null)
120             newCoroutineContext(this.coroutineContext + reactorContext + mdcContext)
121         else
122             newCoroutineContext(this.coroutineContext + reactorContext)
123     } else this.coroutineContext
124     // Execute the block with new and old context
125     withContext(newContext) {
126         block()
127     }
128 }
129
130 @Deprecated(
131     message = "Now CDS supports Coruoutin rest controller",
132     replaceWith = ReplaceWith("mdcWebCoroutineScope")
133 )
134 /** Used in Rest controller API methods to populate MDC context to nested coroutines from reactor web filter context. */
135 @UseExperimental(InternalCoroutinesApi::class)
136 fun <T> monoMdc(
137     context: CoroutineContext = EmptyCoroutineContext,
138     block: suspend CoroutineScope.() -> T?
139 ): Mono<T> = Mono.create { sink ->
140
141     val reactorContext = (context[ReactorContext]?.context?.putAll(sink.currentContext())
142         ?: sink.currentContext()).asCoroutineContext()
143     /** Populate MDC context only if present in Reactor Context */
144     val newContext = if (!reactorContext.context.isEmpty &&
145         reactorContext.context.hasKey(MDCContext)
146     ) {
147         val mdcContext = reactorContext.context.get<MDCContext>(MDCContext)
148         GlobalScope.newCoroutineContext(context + reactorContext + mdcContext)
149     } else GlobalScope.newCoroutineContext(context + reactorContext)
150
151     val coroutine = MonoMDCCoroutine(newContext, sink)
152     sink.onDispose(coroutine)
153     coroutine.start(CoroutineStart.DEFAULT, coroutine, block)
154 }
155
156 @InternalCoroutinesApi
157 class MonoMDCCoroutine<in T>(
158     parentContext: CoroutineContext,
159     private val sink: MonoSink<T>
160 ) : AbstractCoroutine<T>(parentContext, true), Disposable {
161
162     private var disposed = false
163
164     override fun onCompleted(value: T) {
165         if (!disposed) {
166             if (value == null) sink.success() else sink.success(value)
167         }
168     }
169
170     override fun onCancelled(cause: Throwable, handled: Boolean) {
171         if (!disposed) {
172             sink.error(cause)
173         } else if (!handled) {
174             handleCoroutineException(context, cause)
175         }
176     }
177
178     override fun dispose() {
179         disposed = true
180         cancel()
181     }
182
183     override fun isDisposed(): Boolean = disposed
184 }