Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .java-version
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
17.0
8 changes: 8 additions & 0 deletions flume-ng-node/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@
<pmd.maxAllowedViolations>5</pmd.maxAllowedViolations>
<module.name>org.apache.flume.node</module.name>
<junit-jupiter.version>6.1.3</junit-jupiter.version>
<snake-yaml.version>3.2</snake-yaml.version>
</properties>

<dependencies>
Expand Down Expand Up @@ -100,6 +101,13 @@
<groupId>org.apache.commons</groupId>
<artifactId>commons-text</artifactId>
</dependency>

<dependency>
<groupId>org.snakeyaml</groupId>
<artifactId>snakeyaml-engine</artifactId>
<version>${snake-yaml.version}</version>
<optional>true</optional>

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think it is fine to add it as required dependency.

</dependency>
<!-- For ThreadSafe and GuardedBy annotations -->
<dependency>
<groupId>com.google.code.findbugs</groupId>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,6 @@ public void handleConfigurationEvent(MaterializedConfiguration conf) {
startAllComponents(conf);
} catch (InterruptedException e) {
logger.info("Interrupted while trying to handle configuration event");
return;
} finally {
// If interrupted while trying to lock, we don't own the lock, so must not attempt to unlock
if (lifecycleLock.isHeldByCurrentThread()) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,10 +23,11 @@
*/
public interface ConfigurationSource {

static final String PROPERTIES = "properties";
static final String JSON = "json";
static final String YAML = "yaml";
static final String XML = "xml";
String PROPERTIES = "properties";
String JSON = "json";
String YAML = "yaml";
String YML = "yml";
String XML = "xml";

/**
* Returns the InputStream if it hasn't already been processed.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@
import org.apache.flume.conf.FlumeConfiguration;
import org.apache.flume.lifecycle.LifecycleAware;
import org.apache.flume.lifecycle.LifecycleState;
import org.apache.flume.node.internal.YamlConfigConverter;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

Expand Down Expand Up @@ -186,6 +187,7 @@ public class UriConfigurationProvider extends AbstractConfigurationProvider impl
private final EventBus eventBus;
private final int interval;
private final CounterGroup counterGroup;
private final boolean isYamlSupported;
private LifecycleState lifecycleState = LifecycleState.IDLE;
private ScheduledExecutorService executorService;

Expand All @@ -201,6 +203,14 @@ public UriConfigurationProvider(
this.eventBus = eventBus;
this.interval = pollInterval;
counterGroup = new CounterGroup();
boolean isYaml;
try {
Class.forName("org.snakeyaml.engine.v2.api.Load");
isYaml = true;
} catch (Exception exception) {
isYaml = false;
}
isYamlSupported = isYaml;
Comment on lines +206 to +213

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

…which of course will remove the need for reflection.

}

@Override
Expand Down Expand Up @@ -256,6 +266,15 @@ public FlumeConfiguration getFlumeConfiguration() {
switch (configurationSource.getExtension()) {
case ConfigurationSource.JSON:
case ConfigurationSource.YAML:
case ConfigurationSource.YML: {
if (isYamlSupported) {
properties = YamlConfigConverter.convertYamlToProperties(is);

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We should append the properties from multiple sources instead of replacing them.

Suggested change
properties = YamlConfigConverter.convertYamlToProperties(is);
properties.putAll(YamlConfigConverter.convertYamlToProperties(is));

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is going to be my next PR.

} else {
logger.warn(
"File extension type {} is unsupported", configurationSource.getExtension());
}
break;
}
case ConfigurationSource.XML: {
logger.warn("File extension type {} is unsupported", configurationSource.getExtension());
break;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,116 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to you under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.flume.node.internal;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import org.snakeyaml.engine.v2.api.Load;
import org.snakeyaml.engine.v2.api.LoadSettings;

/**
* Converts YAML and/or JSON files into Java properties that can be consumed by the UriConfigurationProvider.
* This uses version 3.x of SnakeYaml that is hosted at https://codeberg.org/snakeyaml/snakeyaml-engine
* and supports YAML 1.2.
*/
public class YamlConfigConverter {

public static Properties convertYamlToProperties(InputStream yamlInputStream) {
Properties properties = new Properties();

LoadSettings settings = LoadSettings.builder().build();
Load load = new Load(settings);

// 2. Load the YAML content into basic Java structures
Object yamlData = load.loadFromInputStream(yamlInputStream);

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This can throw a YamlEngineException, which, unlike Properties.load will not be caught in the UriConfigurationProvider loop.

If one source is defective, the entire configuration will fail.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I will fix this in the next PR.


// 3. Recursively flatten the data structure
if (yamlData instanceof Map) {
flattenMap("", (Map<?, ?>) yamlData, properties);
} else if (yamlData != null) {
throw new IllegalArgumentException("Root YAML element must be a mapping object.");
}

return properties;
}

private static void flattenMap(String prefix, Map<?, ?> map, Properties properties) {
map.forEach((key, value) -> {
String currentKey = prefix.isEmpty() ? String.valueOf(key) : prefix + "." + key;

if (value instanceof Map) {
Map<?, ?> childMap = (Map<?, ?>) value;
if (!prefix.isEmpty() && isComponentMap(childMap)) {
properties.setProperty(currentKey, String.join(" ", keyNames(childMap)));
}
flattenMap(currentKey, childMap, properties);
} else if (value instanceof List) {
flattenList(currentKey, (List<?>) value, properties);
} else if (value != null) {
properties.setProperty(currentKey, String.valueOf(value));
}
});
}

/**
* Determines whether a Map represents a set of named components, such as the sources, channels
* or sinks of an agent. This is the case when every key is a String and every value is a Map.
*/
private static boolean isComponentMap(Map<?, ?> map) {
if (map.isEmpty()) {
return false;
}
for (Map.Entry<?, ?> entry : map.entrySet()) {
if (!(entry.getKey() instanceof String) || !(entry.getValue() instanceof Map)) {
return false;
}
}
return true;
}

private static List<String> keyNames(Map<?, ?> map) {
List<String> names = new ArrayList<>(map.size());
map.keySet().forEach(key -> names.add((String) key));
return names;
}

private static void flattenList(String prefix, List<?> list, Properties properties) {
// Flume expects a list of simple values, such as channel names, as a space separated value.
if (list.stream().noneMatch(value -> value instanceof Map || value instanceof List)) {
List<String> values = new ArrayList<>(list.size());
list.stream().filter(value -> value != null).forEach(value -> values.add(String.valueOf(value)));
if (!values.isEmpty()) {
properties.setProperty(prefix, String.join(" ", values));
}
return;
}
for (int i = 0; i < list.size(); i++) {
Object value = list.get(i);
String currentKey = prefix + "[" + i + "]";

if (value instanceof Map) {
flattenMap(currentKey, (Map<?, ?>) value, properties);
} else if (value instanceof List) {
flattenList(currentKey, (List<?>) value, properties);
} else if (value != null) {
properties.setProperty(currentKey, String.valueOf(value));
}
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -212,13 +212,15 @@ public Void answer(InvocationOnMock invocation) throws Throwable {

@Test
public void testFlumeInit() throws Exception {
File configFile = new File(baseDir, "flume-conf-init.properties");
Files.copy(
new File(getClass()
.getClassLoader()
.getResource("flume-conf-init.properties")
.getFile()),
configFile);
for (String fileName :
new String[] {"flume-conf-init.properties", "flume-conf-init.yml", "flume-conf-init.json"}) {
runFlumeInit(fileName);
}
}

private void runFlumeInit(String fileName) throws Exception {
File configFile = new File(baseDir, fileName);
Files.copy(new File(getClass().getClassLoader().getResource(fileName).getFile()), configFile);
ConfigurationSource source = new FileConfigurationSource(configFile.toURI());
List<ConfigurationSource> sourceList = new ArrayList<>();
sourceList.add(source);
Expand All @@ -227,12 +229,12 @@ public void testFlumeInit() throws Exception {
List<LifecycleAware> components = Lists.newArrayList();
Application application = new Application(components);
MaterializedConfiguration configuration = configurationProvider.getConfiguration();
Assert.assertNotNull("Unable to create configuration", configuration);
Assert.assertNotNull("Unable to create configuration from " + fileName, configuration);
application.handleConfigurationEvent(configuration);
application.start();
Map<String, Channel> channels = configuration.getChannels();
Channel channel = channels.get("processedChannel");
Assert.assertNotNull("Channel not found", channel);
Assert.assertNotNull("Channel not found using " + fileName, channel);
Map<String, SourceRunner> sourceRunners = configuration.getSourceRunners();
Assert.assertNotNull("No source runners", sourceRunners);
SourceRunner runner = sourceRunners.get("source1");
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to you under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.flume.node.internal;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.fail;

import java.io.FileInputStream;
import java.util.Properties;
import org.junit.jupiter.api.Test;

public class YamlConfigConverterTest {

@Test
public void testYaml() {
try {
FileInputStream is = new FileInputStream("target/test-classes/flume-conf-init.yml");
Properties props = YamlConfigConverter.convertYamlToProperties(is);
assertNotNull(props);
is = new FileInputStream("target/test-classes/flume-conf-init.properties");
Properties properties = new Properties();
properties.load(is);
System.out.println(props.size() + " properties");
for (String name : props.stringPropertyNames()) {
System.out.println(name + ": " + props.get(name));
}
assertEquals(properties, props);
assertNull(props.getProperty("host1"));
} catch (Exception ex) {
fail("Unable to convert YAML to properties: " + ex.getMessage());
}
}

@Test
public void testJson() {
try {
FileInputStream is = new FileInputStream("target/test-classes/flume-conf-init.json");
Properties props = YamlConfigConverter.convertYamlToProperties(is);
assertNotNull(props);
is = new FileInputStream("target/test-classes/flume-conf-init.properties");
Properties properties = new Properties();
properties.load(is);
assertEquals(properties, props);
} catch (Exception ex) {
fail("Unable to convert JSON to properties: " + ex.getMessage());
}
}
}
38 changes: 38 additions & 0 deletions flume-ng-node/src/test/resources/flume-conf-init.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
{
"host1": {
"sources": {
"source1": {
"type": "org.apache.flume.source.LocalSource",
"channels": [
"channel1"
],
"totalEvents": 5,
"backoffSleepIncrement": 50
},
"processedSource": {
"type": "org.apache.flume.source.LocalSource",
"channels": [
"processedChannel"
]
}
},
"channels": {
"channel1": {
"type": "memory",
"capacity": 10000
},
"processedChannel": {
"type": "memory",
"capacity": 10000
}
},
"sinks": {
"sink1": {
"type": "org.apache.flume.sink.NullInitSink",
"batchSize": 1,
"targetSource": "processedSource",
"channel": "channel1"
}
}
}
}
Loading
Loading