Add message prioritization module
[ccsdk/cds.git] / ms / blueprintsprocessor / functions / message-prioritizaion / src / main / kotlin / org / onap / ccsdk / cds / blueprintsprocessor / functions / message / prioritization / topology / MessagePrioritizeProcessor.kt
1 /*
2  * Copyright © 2018-2019 AT&T Intellectual Property.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 package org.onap.ccsdk.cds.blueprintsprocessor.functions.message.prioritization.topology
18
19 import org.apache.kafka.streams.processor.Cancellable
20 import org.apache.kafka.streams.processor.ProcessorContext
21 import org.apache.kafka.streams.processor.PunctuationType
22 import org.apache.kafka.streams.processor.To
23 import org.onap.ccsdk.cds.blueprintsprocessor.functions.message.prioritization.AbstractMessagePrioritizeProcessor
24 import org.onap.ccsdk.cds.blueprintsprocessor.functions.message.prioritization.MessagePrioritizationConstants
25 import org.onap.ccsdk.cds.blueprintsprocessor.functions.message.prioritization.MessageState
26 import org.onap.ccsdk.cds.blueprintsprocessor.functions.message.prioritization.db.MessagePrioritization
27 import org.onap.ccsdk.cds.blueprintsprocessor.functions.message.prioritization.utils.MessageCorrelationUtils
28 import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintProcessorException
29 import org.onap.ccsdk.cds.controllerblueprints.core.logger
30 import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils
31 import java.time.Duration
32 import java.util.*
33
34
35 open class MessagePrioritizeProcessor : AbstractMessagePrioritizeProcessor<ByteArray, ByteArray>() {
36
37     private val log = logger(MessagePrioritizeProcessor::class)
38
39     lateinit var expiryCancellable: Cancellable
40     lateinit var cleanCancellable: Cancellable
41
42     override suspend fun processNB(key: ByteArray, value: ByteArray) {
43         log.info("***** received in prioritize processor key(${String(key)})")
44         val data = JacksonUtils.readValue(String(value), MessagePrioritization::class.java)
45                 ?: throw BluePrintProcessorException("failed to convert")
46         // Save the Message
47         messagePrioritizationStateService.saveMessage(data)
48         handleCorrelationAndNextStep(data)
49
50     }
51
52     override fun init(context: ProcessorContext) {
53         super.init(context)
54         /** set up expiry marking cron */
55         initializeExpiryPunctuator()
56         /** Set up cleaning records cron */
57         initializeCleanPunctuator()
58     }
59
60     override fun close() {
61         log.info("closing prioritization processor applicationId(${processorContext.applicationId()}), " +
62                 "taskId(${processorContext.taskId()})")
63         expiryCancellable.cancel()
64         cleanCancellable.cancel()
65     }
66
67     open fun initializeExpiryPunctuator() {
68         val expiryPunctuator = MessagePriorityExpiryPunctuator(messagePrioritizationStateService)
69         expiryPunctuator.processorContext = processorContext
70         expiryPunctuator.configuration = prioritizationConfiguration
71         val expiryConfiguration = prioritizationConfiguration.expiryConfiguration
72         expiryCancellable = processorContext.schedule(Duration.ofMillis(expiryConfiguration.frequencyMilli),
73                 PunctuationType.WALL_CLOCK_TIME, expiryPunctuator)
74         log.info("Expiry punctuator setup complete with frequency(${expiryConfiguration.frequencyMilli})mSec")
75     }
76
77     open fun initializeCleanPunctuator() {
78         val cleanPunctuator = MessagePriorityCleanPunctuator(messagePrioritizationStateService)
79         cleanPunctuator.processorContext = processorContext
80         cleanPunctuator.configuration = prioritizationConfiguration
81         val cleanConfiguration = prioritizationConfiguration.cleanConfiguration
82         cleanCancellable = processorContext.schedule(Duration.ofDays(cleanConfiguration.expiredRecordsHoldDays.toLong()),
83                 PunctuationType.WALL_CLOCK_TIME, cleanPunctuator)
84         log.info("Clean punctuator setup complete with expiry " +
85                 "hold(${cleanConfiguration.expiredRecordsHoldDays})days")
86     }
87
88     open suspend fun handleCorrelationAndNextStep(messagePrioritization: MessagePrioritization) {
89         /** Check correlation enabled and correlation field has populated */
90         if (!messagePrioritization.correlationId.isNullOrBlank()) {
91             val id = messagePrioritization.id
92             val group = messagePrioritization.group
93             val correlationId = messagePrioritization.correlationId!!
94             val types = getGroupCorrelationTypes(messagePrioritization)
95             log.info("checking correlation for message($id), group($group), types($types), " +
96                     "correlation id($correlationId)")
97
98             /** Get all previously received messages from database for group and optional types and correlation Id */
99             val waitingCorrelatedStoreMessages = messagePrioritizationStateService.getCorrelatedMessages(group,
100                     arrayListOf(MessageState.NEW.name, MessageState.WAIT.name), types, correlationId)
101
102             /** If multiple records found, then check correlation */
103             if (!waitingCorrelatedStoreMessages.isNullOrEmpty() && waitingCorrelatedStoreMessages.size > 1) {
104                 /** Check all correlation satisfies */
105                 val correlationResults = MessageCorrelationUtils
106                         .correlatedMessagesWithTypes(waitingCorrelatedStoreMessages, types)
107
108                 if (correlationResults.correlated) {
109                     /** Correlation  satisfied */
110                     val correlatedIds = waitingCorrelatedStoreMessages.map { it.id }.joinToString(",")
111                     /**  Send only correlated ids to next processor */
112                     this.processorContext.forward(UUID.randomUUID().toString(), correlatedIds,
113                             To.child(MessagePrioritizationConstants.PROCESSOR_AGGREGATE))
114                 } else {
115                     /** Correlation not satisfied */
116                     log.trace("correlation not matched : ${correlationResults.message}")
117                     val waitMessageIds = waitingCorrelatedStoreMessages.map { it.id }
118                     // Update the Message state to Wait
119                     messagePrioritizationStateService.setMessagesState(waitMessageIds, MessageState.WAIT.name)
120                 }
121             } else {
122                 /** received first message of group and correlation Id, update the message with wait state */
123                 messagePrioritizationStateService.setMessageState(messagePrioritization.id, MessageState.WAIT.name)
124             }
125         } else {
126             // No Correlation check needed, simply forward to next processor.
127             messagePrioritizationStateService.setMessageState(messagePrioritization.id, MessageState.PRIORITIZED.name)
128             this.processorContext.forward(messagePrioritization.id, messagePrioritization.id,
129                     To.child(MessagePrioritizationConstants.PROCESSOR_AGGREGATE))
130         }
131     }
132
133     /** If consumer wants specific correlation with respect to group and types, then populate the specific types,
134      * otherwise correlation happens with group and correlationId */
135     open fun getGroupCorrelationTypes(messagePrioritization: MessagePrioritization): List<String>? {
136         return null
137     }
138 }