SettingsLoader.kt 6.96 KB
Newer Older
Jonas Waeber's avatar
Jonas Waeber committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
/*
 * sftp-reader
 * Copyright (C) 2020  Memobase Project
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
 */
package org.memobase

import org.apache.kafka.clients.producer.ProducerConfig
import org.apache.kafka.common.serialization.StringSerializer
import org.apache.logging.log4j.LogManager
import org.snakeyaml.engine.v2.api.Load
import org.snakeyaml.engine.v2.api.LoadSettings
import org.snakeyaml.engine.v2.exceptions.MissingEnvironmentVariableException
import java.io.File
import java.io.FileInputStream
import java.util.*
import kotlin.system.exitProcess


class SettingsLoader {
    private val log = LogManager.getLogger("SettingsLoader")

    private fun loadYaml(): Any {


        val settings = LoadSettings.builder().setEnvConfig(Optional.of(CustomEnvConfig())).build()
        val load = Load(settings)
        try {
            val file = File("/configs/app.yml")
            return if (file.isFile) {
                load.loadFromInputStream(FileInputStream(file))
            }
            else {
                log.warn("Loading default properties in app.yml from classpath!")
                load.loadFromInputStream(ClassLoader.getSystemResourceAsStream("app.yml"))
            }
        } catch (ex: MissingEnvironmentVariableException) {
            log.error(ex.message)
            exitProcess(1)
        }

    }

    private val rawKafkaProperties: Map<String, String>
    val topic: String
    val appSettings: Map<String, String>
    val sftpSettings: Map<String, String>
    val kafkaProducerProperties = Properties()

    init {
        val rawYaml = loadYaml()
        try {
            val mappedYaml = rawYaml as Map<String, Any>
            val kafkaOptions = mappedYaml["kafka"] as Map<String, Any>
            val topics = kafkaOptions["topic"] as Map<String, String>
            topic = topics["out"].orEmpty()
            if (topic.isEmpty()) {
                throw MissingSettingException("kafka.topic.out")
            }
            rawKafkaProperties = kafkaOptions["producer"] as Map<String, String>

            appSettings = rawYaml["app"] as Map<String, String>
            ensurePropertyIsSet("directory", appSettings)

            sftpSettings = rawYaml["sftp"] as Map<String, String>
            ensurePropertyIsSet("host", sftpSettings)
            ensurePropertyIsSet("port", sftpSettings)
            ensurePropertyIsSet("user", sftpSettings)
            ensurePropertyIsSet("password", sftpSettings)
            ensurePropertyIsSet("fingerprint", sftpSettings)

        } catch (ex: ClassCastException) {
            ex.printStackTrace()
            log.error("The properties file has an invalid structure: $ex")
            exitProcess(1)
        } catch (ex: MissingSettingException) {
            log.error(ex.message)
            exitProcess(1)
        }
        initializeKafkaProperties()
    }

    private fun ensurePropertyIsSet(setting: String, settings: Map<String, String>) {
        if (settings[setting].isNullOrEmpty()) {
          throw MissingSettingException(setting)
        }
    }

    private fun initializeKafkaProperties() {
        setKafkaProperty(ProducerConfig.CLIENT_ID_CONFIG, abortIfMissing = true)
        setKafkaProperty(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, abortIfMissing = true)
        setKafkaProperty(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer::class.java)
        setKafkaProperty(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer::class.java)
        setKafkaProperty(ProducerConfig.BATCH_SIZE_CONFIG, 16384)
        setKafkaProperty(ProducerConfig.BUFFER_MEMORY_CONFIG, 33445532)
        setKafkaProperty(ProducerConfig.LINGER_MS_CONFIG, 1)
        setKafkaProperty(ProducerConfig.ENABLE_IDEMPOTENCE_CONFIG, true)
        setKafkaProperty(ProducerConfig.ACKS_CONFIG)
        setKafkaProperty(ProducerConfig.COMPRESSION_TYPE_CONFIG, "zstd")
        setKafkaProperty(ProducerConfig.TRANSACTION_TIMEOUT_CONFIG)
        setKafkaProperty(ProducerConfig.TRANSACTIONAL_ID_CONFIG)
        setKafkaProperty(ProducerConfig.CONNECTIONS_MAX_IDLE_MS_CONFIG)
        setKafkaProperty(ProducerConfig.DELIVERY_TIMEOUT_MS_CONFIG)
        setKafkaProperty(ProducerConfig.SEND_BUFFER_CONFIG)
        setKafkaProperty(ProducerConfig.INTERCEPTOR_CLASSES_CONFIG)
        setKafkaProperty(ProducerConfig.RETRY_BACKOFF_MS_CONFIG)
        setKafkaProperty(ProducerConfig.RETRIES_CONFIG)
        setKafkaProperty(ProducerConfig.REQUEST_TIMEOUT_MS_CONFIG)
        setKafkaProperty(ProducerConfig.PARTITIONER_CLASS_CONFIG)
        setKafkaProperty(ProducerConfig.METRIC_REPORTER_CLASSES_CONFIG)
        setKafkaProperty(ProducerConfig.METRICS_NUM_SAMPLES_CONFIG)
        setKafkaProperty(ProducerConfig.METRICS_RECORDING_LEVEL_CONFIG)
        setKafkaProperty(ProducerConfig.METRICS_SAMPLE_WINDOW_MS_CONFIG)
        setKafkaProperty(ProducerConfig.MAX_BLOCK_MS_CONFIG)
        setKafkaProperty(ProducerConfig.MAX_IN_FLIGHT_REQUESTS_PER_CONNECTION)
        setKafkaProperty(ProducerConfig.MAX_REQUEST_SIZE_CONFIG)
        setKafkaProperty(ProducerConfig.METADATA_MAX_AGE_CONFIG)
        setKafkaProperty(ProducerConfig.RECEIVE_BUFFER_CONFIG)
        setKafkaProperty(ProducerConfig.RECONNECT_BACKOFF_MAX_MS_CONFIG)
        setKafkaProperty(ProducerConfig.RECONNECT_BACKOFF_MS_CONFIG)

    }
    private fun setKafkaProperty(propertyName: String, defaultValue: Any? = null, abortIfMissing: Boolean = false) {

        val envProperty = propertyName.replace("\\.".toRegex(), "_").toUpperCase()
        when {
            System.getenv(envProperty) != null -> {
                log.debug("Found value for property $propertyName in environment variable $envProperty.")
                kafkaProducerProperties.setProperty(propertyName, System.getenv(envProperty))
            }
            rawKafkaProperties.containsKey(propertyName) -> {
                log.debug("Found value for property $propertyName in app.yml file.")
                kafkaProducerProperties.setProperty(propertyName, rawKafkaProperties[propertyName])
            }
            defaultValue != null -> {
                log.debug("Using default value $defaultValue for $propertyName.")
                kafkaProducerProperties[propertyName] = defaultValue
            }
            abortIfMissing -> {
                log.error("Required producer property $propertyName was not set! Aborting...")
                exitProcess(1)
            }
            else -> log.trace("No value for property $propertyName found")
        }
    }
}