World's most powerful open data catalog for building a high-performance, geo-distributed and federated metadata lake.
Java ai-catalogdata-catalogdatalakefederated-querylakehousemetadatametalakemodel-catalogopendatacatalogskycomputingstratosphere
[#27] feat(core): add config system (#29)
Jerry Shao2da3f76824ef
diff --git a/core/src/main/java/com/datastrato/graviton/Config.java b/core/src/main/java/com/datastrato/graviton/Config.javanew file mode 100644index 0000000000..7bce3a4f72--- /dev/null+++ b/core/src/main/java/com/datastrato/graviton/Config.java@@ -0,0 +1,116 @@+package com.datastrato.graviton;++import com.datastrato.graviton.config.ConfigEntry;+import com.google.common.annotations.VisibleForTesting;+import com.google.common.collect.Maps;+import java.io.File;+import java.io.IOException;+import java.io.InputStream;+import java.nio.file.Files;+import java.util.Map;+import java.util.NoSuchElementException;+import java.util.Optional;+import java.util.Properties;+import java.util.concurrent.ConcurrentHashMap;+import java.util.concurrent.ConcurrentMap;+import org.slf4j.Logger;+import org.slf4j.LoggerFactory;++public abstract class Config {++ private static final Logger LOG = LoggerFactory.getLogger(Config.class);++ private static final String CONFIG_PREPEND = "graviton.";++ private final ConcurrentMap<String, String> configMap;++ public Config(boolean loadDefaults) {+ configMap = new ConcurrentHashMap<>();+ if (loadDefaults) {+ loadFromProperties(System.getProperties());+ }+ }++ public Config() {+ this(true);+ }++ public Config loadFromFile(String name) throws IOException {+ String confDir =+ Optional.ofNullable(System.getenv("GRAVITON_CONF_DIR"))+ .orElse(+ Optional.ofNullable(System.getenv("GRAVITON_HOME"))+ .map(s -> s + File.separator + "conf")+ .orElse(null));++ if (confDir == null) {+ throw new IllegalArgumentException("GRAVITON_CONF_DIR or GRAVITON_HOME not set");+ }++ File confFile = new File(confDir + File.separator + name);+ if (!confFile.exists()) {+ throw new IllegalArgumentException(+ "Config file " + confFile.getAbsolutePath() + " not found");+ }++ Properties properties = loadPropertiesFromFile(confFile);+ loadFromProperties(properties);++ return this;+ }++ public <T> T get(ConfigEntry<T> entry) throws NoSuchElementException {+ if (entry.isDeprecated()) {+ LOG.warn("Config {} is deprecated.", entry.getKey());+ if (!entry.getAlternatives().isEmpty()) {+ LOG.warn("Please use {} instead.", String.join(", ", entry.getAlternatives()));+ }+ }++ return entry.readFrom(configMap);+ }++ public <T> void set(ConfigEntry<T> entry, T value) {+ if (entry.isDeprecated()) {+ LOG.warn("Config {} is deprecated.", entry.getKey());+ if (!entry.getAlternatives().isEmpty()) {+ LOG.warn("Please use {} instead.", String.join(", ", entry.getAlternatives()));+ }+ }++ if (value == null) {+ LOG.warn("Config {} value to set is null, ignore setting to Config.", entry.getKey());+ }++ entry.writeTo(configMap, value);+ }++ private void loadFromMap(Map<String, String> map) {+ map.forEach(+ (k, v) -> {+ String trimmedK = k.trim();+ String trimmedV = v.trim();+ if (!trimmedK.isEmpty() && !trimmedV.isEmpty() && trimmedK.startsWith(CONFIG_PREPEND)) {+ configMap.put(trimmedK, trimmedV);+ }+ });+ }++ @VisibleForTesting+ void loadFromProperties(Properties properties) {+ loadFromMap(Maps.fromProperties(properties));+ }++ @VisibleForTesting+ Properties loadPropertiesFromFile(File file) throws IOException {+ Properties properties = new Properties();+ try (InputStream in = Files.newInputStream(file.toPath())) {+ properties.load(in);+ return properties;++ } catch (Exception e) {+ LOG.error("Failed to load properties from " + file.getAbsolutePath(), e);+ throw new IOException("Failed to load properties from " + file.getAbsolutePath(), e);+ }+ }+}diff --git a/core/src/main/java/com/datastrato/graviton/config/ConfigBuilder.java b/core/src/main/java/com/datastrato/graviton/config/ConfigBuilder.javanew file mode 100644index 0000000000..4bdc3b54cc--- /dev/null+++ b/core/src/main/java/com/datastrato/graviton/config/ConfigBuilder.java@@ -0,0 +1,125 @@+package com.datastrato.graviton.config;++import java.util.Collections;+import java.util.List;+import java.util.Optional;+import java.util.function.Function;++public class ConfigBuilder {++ private String key;++ private List<String> alternatives;++ private String doc;++ private String version;++ private boolean isPublic;++ private boolean isDeprecated;++ public ConfigBuilder(String key) {+ this.key = key;++ this.alternatives = Collections.emptyList();+ this.doc = "";+ this.version = "0.1.0";+ this.isPublic = true;+ this.isDeprecated = false;+ }++ public ConfigBuilder alternatives(List<String> alternatives) {+ this.alternatives = alternatives;+ return this;+ }++ public ConfigBuilder doc(String doc) {+ this.doc = doc;+ return this;+ }++ public ConfigBuilder version(String version) {+ this.version = version;+ return this;+ }++ public ConfigBuilder internal() {+ this.isPublic = false;+ return this;+ }++ public ConfigBuilder deprecated() {+ this.isDeprecated = true;+ return this;+ }++ public ConfigEntry<String> stringConf() {+ ConfigEntry<String> conf =+ new ConfigEntry<>(key, version, doc, alternatives, isPublic, isDeprecated);+ conf.setValueConverter(s -> s);+ conf.setStringConverter(s -> s);++ return conf;+ }++ public ConfigEntry<Integer> intConf() {+ ConfigEntry<Integer> conf =+ new ConfigEntry<>(key, version, doc, alternatives, isPublic, isDeprecated);+ Function<String, Integer> func =+ s -> {+ if (s == null || s.isEmpty()) {+ return null;+ } else {+ return Integer.parseInt(s);+ }+ };+ conf.setValueConverter(func);++ Function<Integer, String> stringFunc =+ t -> Optional.ofNullable(t).map(String::valueOf).orElse(null);+ conf.setStringConverter(stringFunc);++ return conf;+ }++ public ConfigEntry<Long> longConf() {+ ConfigEntry<Long> conf =+ new ConfigEntry<>(key, version, doc, alternatives, isPublic, isDeprecated);+ Function<String, Long> func =+ s -> {+ if (s == null || s.isEmpty()) {+ return null;+ } else {+ return Long.parseLong(s);+ }+ };+ conf.setValueConverter(func);++ Function<Long, String> stringFunc =+ t -> Optional.ofNullable(t).map(String::valueOf).orElse(null);+ conf.setStringConverter(stringFunc);++ return conf;+ }++ public ConfigEntry<Boolean> booleanConf() {+ ConfigEntry<Boolean> conf =+ new ConfigEntry<>(key, version, doc, alternatives, isPublic, isDeprecated);+ Function<String, Boolean> func =+ s -> {+ if (s == null || s.isEmpty()) {+ return null;+ } else {+ return Boolean.parseBoolean(s);+ }+ };+ conf.setValueConverter(func);++ Function<Boolean, String> stringFunc =+ t -> Optional.ofNullable(t).map(String::valueOf).orElse(null);+ conf.setStringConverter(stringFunc);++ return conf;+ }+}diff --git a/core/src/main/java/com/datastrato/graviton/config/ConfigEntry.java b/core/src/main/java/com/datastrato/graviton/config/ConfigEntry.javanew file mode 100644index 0000000000..55f4c80b72--- /dev/null+++ b/core/src/main/java/com/datastrato/graviton/config/ConfigEntry.java@@ -0,0 +1,121 @@+package com.datastrato.graviton.config;++import java.util.List;+import java.util.Map;+import java.util.NoSuchElementException;+import java.util.Optional;+import java.util.function.Function;+import lombok.Getter;+import org.slf4j.Logger;+import org.slf4j.LoggerFactory;++public class ConfigEntry<T> {++ private static final Logger LOG = LoggerFactory.getLogger(ConfigEntry.class);++ @Getter private String key;++ @Getter private List<String> alternatives;++ @Getter private T defaultValue;++ private Function<String, T> valueConverter;++ private Function<T, String> stringConverter;++ @Getter private String doc;++ @Getter private String version;++ @Getter private boolean isPublic;++ @Getter private boolean isDeprecated;++ private boolean isOptional;++ ConfigEntry(+ String key,+ String version,+ String doc,+ List<String> alternatives,+ boolean isPublic,+ boolean isDeprecated) {+ this.key = key;+ this.version = version;+ this.doc = doc;+ this.alternatives = alternatives;+ this.isPublic = isPublic;+ this.isDeprecated = isDeprecated;+ this.isOptional = false;+ }++ void setValueConverter(Function<String, T> valueConverter) {+ this.valueConverter = valueConverter;+ }++ void setStringConverter(Function<T, String> stringConverter) {+ this.stringConverter = stringConverter;+ }++ void setDefaultValue(T t) {+ this.defaultValue = t;+ }++ void setOptional() {+ this.isOptional = true;+ }++ public ConfigEntry<T> createWithDefault(T t) {+ ConfigEntry<T> conf =+ new ConfigEntry<>(key, version, doc, alternatives, isPublic, isDeprecated);+ conf.setValueConverter(valueConverter);+ conf.setStringConverter(stringConverter);+ conf.setDefaultValue(t);++ return conf;+ }++ public ConfigEntry<Optional<T>> createWithOptional() {+ ConfigEntry<Optional<T>> conf =+ new ConfigEntry<>(key, version, doc, alternatives, isPublic, isDeprecated);+ conf.setValueConverter(s -> Optional.ofNullable(valueConverter.apply(s)));+ // null value should not be possible unless the user explicitly sets it+ conf.setStringConverter(t -> t.map(stringConverter).orElse(null));+ conf.setOptional();++ return conf;+ }++ public T readFrom(Map<String, String> properties) throws NoSuchElementException {+ String value = properties.get(key);+ if (value == null) {+ for (String alternative : alternatives) {+ value = properties.get(alternative);+ if (value != null) {+ break;+ }+ }+ }++ if (value == null) {+ if (defaultValue != null) {+ return defaultValue;+ } else if (!isOptional) {+ throw new NoSuchElementException("No configuration found for key " + key);+ }+ }++ return valueConverter.apply(value);+ }++ public void writeTo(Map<String, String> properties, T value) {+ String stringValue = stringConverter.apply(value);+ if (stringValue == null) {+ // We don't want user to set a null value to config, so this basically will not happen;+ LOG.warn("Config {} value to set is null, ignore setting to Config.", stringValue);+ return;+ }++ properties.put(key, stringValue);+ }+}diff --git a/core/src/test/java/com/datastrato/graviton/TestConfig.java b/core/src/test/java/com/datastrato/graviton/TestConfig.javanew file mode 100644index 0000000000..ce4a1ca96e--- /dev/null+++ b/core/src/test/java/com/datastrato/graviton/TestConfig.java@@ -0,0 +1,135 @@+package com.datastrato.graviton;++import com.datastrato.graviton.config.ConfigBuilder;+import com.datastrato.graviton.config.ConfigEntry;+import java.io.File;+import java.io.FileOutputStream;+import java.nio.file.Files;+import java.util.NoSuchElementException;+import java.util.Optional;+import java.util.Properties;+import org.junit.jupiter.api.AfterEach;+import org.junit.jupiter.api.Assertions;+import org.junit.jupiter.api.BeforeEach;+import org.junit.jupiter.api.Test;++public class TestConfig {++ class DummyConfig extends Config {+ public DummyConfig(boolean loadSystemProperties) {+ super(loadSystemProperties);+ }++ public DummyConfig() {+ this(true);+ }+ }++ private final Properties props = new Properties();++ @BeforeEach+ public void setUp() {+ props.setProperty("test", "test");+ props.setProperty("graviton.test.test-string", "test-string");+ props.setProperty("graviton.test.test-int", " 1 ");+ props.setProperty("graviton.test.test-boolean", "true");++ props.forEach((k, v) -> System.setProperty((String) k, (String) v));+ }++ @AfterEach+ public void tearDown() {+ props.forEach((k, v) -> System.clearProperty((String) k));+ }++ @Test+ public void testLoadProperties() {+ ConfigEntry<String> stringConf =+ new ConfigBuilder("test").stringConf().createWithDefault("test-default");+ ConfigEntry<Optional<Integer>> intConf =+ new ConfigBuilder("graviton.test.test-int").intConf().createWithOptional();+ ConfigEntry<String> stringConf1 = new ConfigBuilder("test").stringConf();++ DummyConfig config = new DummyConfig(true);++ // Config "stringConf" will not load into Config, so it will return the default value+ String value = config.get(stringConf);+ Assertions.assertEquals("test-default", value);++ // Config "stringConf1" will not load into Config and it has no default value, so it will+ // throw an exception+ Throwable exception =+ Assertions.assertThrows(NoSuchElementException.class, () -> config.get(stringConf1));+ Assertions.assertEquals("No configuration found for key test", exception.getMessage());++ Optional<Integer> intValue = config.get(intConf);+ Assertions.assertEquals(Optional.of(1), intValue);+ }++ @Test+ public void testLoadFormFile() throws Exception {+ FileOutputStream fos = null;+ try {+ File propsFile = Files.createTempFile("tmp_test", ".properties").toFile();+ fos = new FileOutputStream(propsFile);+ props.store(fos, "test");++ ConfigEntry<String> stringConf =+ new ConfigBuilder("test").stringConf().createWithDefault("test-default");+ ConfigEntry<Integer> intConf = new ConfigBuilder("graviton.test.test-int").intConf();+ ConfigEntry<Boolean> booleanConf =+ new ConfigBuilder("graviton.test.test-boolean").booleanConf();++ // Do not load default system properties, loading from file.+ DummyConfig config = new DummyConfig(false);+ config.loadFromProperties(config.loadPropertiesFromFile(propsFile));++ // Config "stringConf" will not load into Config, so it will return the value from the file+ String value = config.get(stringConf);+ Assertions.assertEquals("test-default", value);++ // Config "intConf" will load into Config, so it will return the value from the file+ Integer intValue = config.get(intConf);+ Assertions.assertEquals(1, intValue);++ // Config "booleanConf" will load into Config, so it will return the value from the file+ Boolean booleanValue = config.get(booleanConf);+ Assertions.assertEquals(true, booleanValue);+ } finally {+ if (fos != null) {+ fos.close();+ fos = null;+ }+ }+ }++ @Test+ public void testGetAndSet() {+ ConfigEntry<Optional<Integer>> intConf =+ new ConfigBuilder("graviton.test.test-int").intConf().createWithOptional();+ ConfigEntry<Boolean> booleanConf =+ new ConfigBuilder("graviton.test.test-boolean").booleanConf().createWithDefault(false);++ DummyConfig config = new DummyConfig(true);++ // Config "intConf" will load into Config, so it will return the value from the system+ // properties+ Optional<Integer> intValue = config.get(intConf);+ Assertions.assertEquals(Optional.of(1), intValue);++ // Config "booleanConf" will load into Config, so it will return the value from the system+ // properties+ Boolean booleanValue = config.get(booleanConf);+ Assertions.assertEquals(true, booleanValue);++ // Set a new value for "booleanConf"+ config.set(booleanConf, false);+ booleanValue = config.get(booleanConf);+ Assertions.assertEquals(false, booleanValue);++ // Set a new value for "intConf"+ config.set(intConf, Optional.of(2));+ intValue = config.get(intConf);+ Assertions.assertEquals(Optional.of(2), intValue);+ }+}diff --git a/core/src/test/java/com/datastrato/graviton/config/TestConfigEntry.java b/core/src/test/java/com/datastrato/graviton/config/TestConfigEntry.javanew file mode 100644index 0000000000..942c331d6e--- /dev/null+++ b/core/src/test/java/com/datastrato/graviton/config/TestConfigEntry.java@@ -0,0 +1,124 @@+package com.datastrato.graviton.config;++import com.google.common.collect.Lists;+import java.util.NoSuchElementException;+import java.util.Optional;+import java.util.concurrent.ConcurrentHashMap;+import java.util.concurrent.ConcurrentMap;+import org.junit.jupiter.api.AfterEach;+import org.junit.jupiter.api.Assertions;+import org.junit.jupiter.api.BeforeEach;+import org.junit.jupiter.api.Test;++public class TestConfigEntry {++ private final ConcurrentMap<String, String> configMap = new ConcurrentHashMap<>();++ @BeforeEach+ public void initializeConfigMap() {+ configMap.put("graviton.test.string", "test-string");+ configMap.put("graviton.test.string.alt1", "test-string1");+ configMap.put("graviton.test.string.alt2", "test-string2");+ }++ @AfterEach+ public void clearConfigMap() {+ configMap.clear();+ }++ @Test+ public void testConfWithDefaultValue() {+ ConfigEntry<String> testConf =+ new ConfigBuilder("graviton.test.string")+ .doc("test")+ .internal()+ .stringConf()+ .createWithDefault("test");+ String value = testConf.readFrom(configMap);+ Assertions.assertEquals("test-string", value);++ ConfigEntry<Integer> testConf1 =+ new ConfigBuilder("graviton.test.int")+ .doc("test")+ .version("1.0")+ .intConf()+ .createWithDefault(10);+ int value1 = testConf1.readFrom(configMap);+ Assertions.assertEquals(10, value1);++ ConfigEntry<Boolean> testConf2 =+ new ConfigBuilder("graviton.test.boolean").booleanConf().createWithDefault(true);+ boolean value2 = testConf2.readFrom(configMap);+ Assertions.assertTrue(value2);+ }++ @Test+ public void testConfWithoutDefaultValue() {+ ConfigEntry<String> testConf =+ new ConfigBuilder("graviton.test.string").doc("test").internal().stringConf();+ String value = testConf.readFrom(configMap);+ Assertions.assertEquals("test-string", value);++ ConfigEntry<Integer> testConf1 = new ConfigBuilder("graviton.test.int.no-exist").intConf();+ Throwable exception =+ Assertions.assertThrows(NoSuchElementException.class, () -> testConf1.readFrom(configMap));+ Assertions.assertEquals(+ "No configuration found for key graviton.test.int.no-exist", exception.getMessage());+ }++ @Test+ public void testConfWithOptionalValue() {+ ConfigEntry<Optional<String>> testConf =+ new ConfigBuilder("graviton.test.no-exist-string").stringConf().createWithOptional();++ Optional<String> value = testConf.readFrom(configMap);+ Assertions.assertEquals(Optional.empty(), value);++ ConfigEntry<Optional<Integer>> testConf1 =+ new ConfigBuilder("graviton.test.no-exist-int").intConf().createWithOptional();++ Optional<Integer> value1 = testConf1.readFrom(configMap);+ Assertions.assertEquals(Optional.empty(), value1);+ }++ @Test+ public void testConfWithAlternatives() {+ ConfigEntry<String> testConf =+ new ConfigBuilder("graviton.test.string")+ .alternatives(+ Lists.newArrayList("graviton.test.string.alt1", "graviton.test.string.alt1"))+ .stringConf()+ .createWithDefault("test");++ String value = testConf.readFrom(configMap);+ Assertions.assertEquals("test-string", value);++ ConfigEntry<String> testConf1 =+ new ConfigBuilder("graviton.test.string.no-exist")+ .alternatives(+ Lists.newArrayList("graviton.test.string.alt1", "graviton.test.string.alt1"))+ .stringConf()+ .createWithDefault("test");++ String value1 = testConf1.readFrom(configMap);+ Assertions.assertEquals("test-string1", value1);+ }++ @Test+ public void testSetConf() {+ ConfigEntry<Integer> testConf =+ new ConfigBuilder("graviton.test.int").intConf().createWithDefault(1);++ testConf.writeTo(configMap, 10);+ Assertions.assertEquals("10", configMap.get("graviton.test.int"));++ ConfigEntry<Optional<Integer>> testConf1 =+ new ConfigBuilder("graviton.test.int1").intConf().createWithOptional();++ testConf1.writeTo(configMap, Optional.of(11));+ Assertions.assertEquals("11", configMap.get("graviton.test.int1"));++ testConf1.writeTo(configMap, Optional.empty());+ Assertions.assertEquals("11", configMap.get("graviton.test.int1"));+ }+}