You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@metron.apache.org by rm...@apache.org on 2016/04/26 16:46:14 UTC
[26/51] [partial] incubator-metron git commit: METRON-113 Project
Reorganization (merrimanr) closes apache/incubator-metron#88
http://git-wip-us.apache.org/repos/asf/incubator-metron/blob/0117987e/metron-platform/metron-enrichment/src/main/java/org/apache/metron/enrichment/lookup/accesstracker/PersistentAccessTracker.java
----------------------------------------------------------------------
diff --git a/metron-platform/metron-enrichment/src/main/java/org/apache/metron/enrichment/lookup/accesstracker/PersistentAccessTracker.java b/metron-platform/metron-enrichment/src/main/java/org/apache/metron/enrichment/lookup/accesstracker/PersistentAccessTracker.java
new file mode 100644
index 0000000..13ecfd5
--- /dev/null
+++ b/metron-platform/metron-enrichment/src/main/java/org/apache/metron/enrichment/lookup/accesstracker/PersistentAccessTracker.java
@@ -0,0 +1,209 @@
+/**
+ * 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.metron.enrichment.lookup.accesstracker;
+
+import org.apache.hadoop.hbase.client.HTableInterface;
+import org.apache.log4j.Logger;
+import org.apache.metron.enrichment.lookup.LookupKey;
+
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.DataInputStream;
+import java.io.DataOutputStream;
+import java.io.IOException;
+import java.util.Map;
+import java.util.Timer;
+import java.util.TimerTask;
+
+public class PersistentAccessTracker implements AccessTracker {
+ private static final Logger LOG = Logger.getLogger(PersistentAccessTracker.class);
+ private static final long serialVersionUID = 1L;
+
+ public static class AccessTrackerKey {
+ String name;
+ String containerName;
+ long timestamp;
+ public AccessTrackerKey(String name, String containerName, long timestamp) {
+ this.name = name;
+ this.containerName = containerName;
+ this.timestamp = timestamp;
+ }
+
+ public byte[] toRowKey() {
+ ByteArrayOutputStream os = new ByteArrayOutputStream();
+ DataOutputStream dos = new DataOutputStream(os);
+ try {
+ dos.writeUTF(name);
+ dos.writeLong(timestamp);
+ dos.writeUTF(containerName);
+ dos.flush();
+ } catch (IOException e) {
+ throw new RuntimeException("Unable to write rowkey: " + this, e);
+ }
+
+ return os.toByteArray();
+ }
+
+ public static byte[] getTimestampScanKey(String name, long timestamp) {
+ ByteArrayOutputStream os = new ByteArrayOutputStream();
+ DataOutputStream dos = new DataOutputStream(os);
+ try {
+ dos.writeUTF(name);
+ dos.writeLong(timestamp);
+ } catch (IOException e) {
+ throw new RuntimeException("Unable to create scan key " , e);
+ }
+
+ return os.toByteArray();
+ }
+
+ public static AccessTrackerKey fromRowKey(byte[] rowKey) {
+ ByteArrayInputStream is = new ByteArrayInputStream(rowKey);
+ DataInputStream dis = new DataInputStream(is);
+ try {
+ String name = dis.readUTF();
+ long timestamp = dis.readLong();
+ String containerName = dis.readUTF();
+ return new AccessTrackerKey(name, containerName, timestamp);
+ } catch (IOException e) {
+ throw new RuntimeException("Unable to read rowkey: ", e);
+ }
+ }
+ }
+
+ private static class Persister extends TimerTask {
+ PersistentAccessTracker tracker;
+ public Persister(PersistentAccessTracker tracker) {
+ this.tracker = tracker;
+ }
+ /**
+ * The action to be performed by this timer task.
+ */
+ @Override
+ public void run() {
+ tracker.persist(false);
+ }
+ }
+
+ Object sync = new Object();
+ HTableInterface accessTrackerTable;
+ String accessTrackerColumnFamily;
+ AccessTracker underlyingTracker;
+ long timestamp = System.currentTimeMillis();
+ String name;
+ String containerName;
+ private Timer timer;
+ long maxMillisecondsBetweenPersists;
+
+ public PersistentAccessTracker( String name
+ , String containerName
+ , HTableInterface accessTrackerTable
+ , String columnFamily
+ , AccessTracker underlyingTracker
+ , long maxMillisecondsBetweenPersists
+ )
+ {
+ this.containerName = containerName;
+ this.accessTrackerTable = accessTrackerTable;
+ this.name = name;
+ this.accessTrackerColumnFamily = columnFamily;
+ this.underlyingTracker = underlyingTracker;
+ this.maxMillisecondsBetweenPersists = maxMillisecondsBetweenPersists;
+ timer = new Timer();
+ if(maxMillisecondsBetweenPersists > 0) {
+ timer.scheduleAtFixedRate(new Persister(this), maxMillisecondsBetweenPersists, maxMillisecondsBetweenPersists);
+ }
+ }
+
+ public void persist(boolean force) {
+ synchronized(sync) {
+ if(force || (System.currentTimeMillis() - timestamp) >= maxMillisecondsBetweenPersists) {
+ //persist
+ try {
+ AccessTrackerUtil.INSTANCE.persistTracker(accessTrackerTable, accessTrackerColumnFamily, new AccessTrackerKey(name, containerName, timestamp), underlyingTracker);
+ timestamp = System.currentTimeMillis();
+ reset();
+ } catch (IOException e) {
+ LOG.error("Unable to persist access tracker.", e);
+ }
+ }
+ }
+ }
+
+ @Override
+ public void logAccess(LookupKey key) {
+ synchronized (sync) {
+ underlyingTracker.logAccess(key);
+ if (isFull()) {
+ persist(true);
+ }
+ }
+ }
+
+ @Override
+ public void configure(Map<String, Object> config) {
+ underlyingTracker.configure(config);
+ }
+
+ @Override
+ public boolean hasSeen(LookupKey key) {
+ synchronized(sync) {
+ return underlyingTracker.hasSeen(key);
+ }
+ }
+
+ @Override
+ public String getName() {
+ return underlyingTracker.getName();
+ }
+
+ @Override
+ public AccessTracker union(AccessTracker tracker) {
+ PersistentAccessTracker t1 = (PersistentAccessTracker)tracker;
+ underlyingTracker = underlyingTracker.union(t1.underlyingTracker);
+ return this;
+ }
+
+ @Override
+ public void reset() {
+ synchronized(sync) {
+ underlyingTracker.reset();
+ }
+ }
+
+ @Override
+ public boolean isFull() {
+ synchronized (sync) {
+ return underlyingTracker.isFull();
+ }
+ }
+
+ @Override
+ public void cleanup() throws IOException {
+ synchronized(sync) {
+ try {
+ persist(true);
+ }
+ catch(Throwable t) {
+ LOG.error("Unable to persist underlying tracker", t);
+ }
+ underlyingTracker.cleanup();
+ accessTrackerTable.close();
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-metron/blob/0117987e/metron-platform/metron-enrichment/src/main/java/org/apache/metron/enrichment/lookup/handler/Handler.java
----------------------------------------------------------------------
diff --git a/metron-platform/metron-enrichment/src/main/java/org/apache/metron/enrichment/lookup/handler/Handler.java b/metron-platform/metron-enrichment/src/main/java/org/apache/metron/enrichment/lookup/handler/Handler.java
new file mode 100644
index 0000000..4ba4de4
--- /dev/null
+++ b/metron-platform/metron-enrichment/src/main/java/org/apache/metron/enrichment/lookup/handler/Handler.java
@@ -0,0 +1,29 @@
+/**
+ * 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.metron.enrichment.lookup.handler;
+
+import org.apache.metron.enrichment.lookup.LookupKey;
+
+import java.io.IOException;
+
+public interface Handler<CONTEXT_T, KEY_T extends LookupKey, RESULT_T> extends AutoCloseable{
+ boolean exists(KEY_T key, CONTEXT_T context, boolean logAccess) throws IOException;
+ RESULT_T get(KEY_T key, CONTEXT_T context, boolean logAccess) throws IOException;
+ Iterable<Boolean> exists(Iterable<KEY_T> key, CONTEXT_T context, boolean logAccess) throws IOException;
+ Iterable<RESULT_T> get(Iterable<KEY_T> key, CONTEXT_T context, boolean logAccess) throws IOException;
+}
http://git-wip-us.apache.org/repos/asf/incubator-metron/blob/0117987e/metron-platform/metron-enrichment/src/main/java/org/apache/metron/enrichment/tldextractor/BasicTldExtractor.java
----------------------------------------------------------------------
diff --git a/metron-platform/metron-enrichment/src/main/java/org/apache/metron/enrichment/tldextractor/BasicTldExtractor.java b/metron-platform/metron-enrichment/src/main/java/org/apache/metron/enrichment/tldextractor/BasicTldExtractor.java
new file mode 100644
index 0000000..016870f
--- /dev/null
+++ b/metron-platform/metron-enrichment/src/main/java/org/apache/metron/enrichment/tldextractor/BasicTldExtractor.java
@@ -0,0 +1,154 @@
+/**
+ * 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.metron.enrichment.tldextractor;
+
+import java.io.BufferedReader;
+import java.io.IOException;
+import java.io.InputStreamReader;
+import java.io.Serializable;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.Comparator;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+public class BasicTldExtractor implements Serializable {
+ private static final long serialVersionUID = -7440226111118873815L;
+ private StringBuilder sb = new StringBuilder();
+
+ private Pattern pattern;
+
+ /**
+ * The inputFile.
+ */
+ private String inputFile ="effective_tld_names.dat";
+
+ public BasicTldExtractor(String filePath) {
+ this.inputFile=filePath;
+ this.init();
+ }
+
+ public BasicTldExtractor() {
+ this.init();
+ }
+
+ private void init(){
+ try {
+ ArrayList<String> terms = new ArrayList<String>();
+
+
+ BufferedReader br = new BufferedReader(new InputStreamReader(
+ getClass().getClassLoader().getResourceAsStream(inputFile)));
+ String s = null;
+ while ((s = br.readLine()) != null) {
+ s = s.trim();
+ if (s.length() == 0 || s.startsWith("//") || s.startsWith("!"))
+ continue;
+ terms.add(s);
+ }
+ Collections.sort(terms, new StringLengthComparator());
+ for (String t : terms)
+ add(t);
+ compile();
+ br.close();
+ } catch (IOException e) {
+ throw new IllegalStateException(e);
+ }
+ }
+ protected void add(String s) {
+ s = s.replace(".", "\\.");
+ s = "\\." + s;
+ if (s.startsWith("*")) {
+ s = s.replace("*", ".+");
+ sb.append(s).append("|");
+ } else {
+ sb.append(s).append("|");
+ }
+ }
+
+ public void compile() {
+ if (sb.length() > 0)
+ sb.deleteCharAt(sb.length() - 1);
+ sb.insert(0, "[^.]+?(");
+ sb.append(")$");
+ pattern = Pattern.compile(sb.toString());
+ sb = null;
+ }
+
+ public String extract2LD(String host) {
+ Matcher m = pattern.matcher(host);
+ if (m.find()) {
+ return m.group(0);
+ }
+ return null;
+ }
+
+ public String extractTLD(String host) {
+ Matcher m = pattern.matcher(host);
+ if (m.find()) {
+ return m.group(1);
+ }
+ return null;
+ }
+
+ public static class StringLengthComparator implements Comparator<String> {
+ public int compare(String s1, String s2) {
+ if (s1.length() > s2.length())
+ return -1;
+ if (s1.length() < s2.length())
+ return 1;
+ return 0;
+ }
+ }
+ /**
+ * Returns the sb.
+ * @return the sb.
+ */
+
+ public StringBuilder getSb() {
+ return sb;
+ }
+
+ /**
+ * Sets the sb.
+ * @param sb the sb.
+ */
+
+ public void setSb(StringBuilder sb) {
+
+ this.sb = sb;
+ }
+ /**
+ * Returns the inputFile.
+ * @return the inputFile.
+ */
+
+ public String getInputFile() {
+ return inputFile;
+ }
+
+ /**
+ * Sets the inputFile.
+ * @param inputFile the inputFile.
+ */
+
+ public void setInputFile(String inputFile) {
+
+ this.inputFile = inputFile;
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-metron/blob/0117987e/metron-platform/metron-enrichment/src/main/java/org/apache/metron/enrichment/utils/EnrichmentUtils.java
----------------------------------------------------------------------
diff --git a/metron-platform/metron-enrichment/src/main/java/org/apache/metron/enrichment/utils/EnrichmentUtils.java b/metron-platform/metron-enrichment/src/main/java/org/apache/metron/enrichment/utils/EnrichmentUtils.java
new file mode 100644
index 0000000..655188c
--- /dev/null
+++ b/metron-platform/metron-enrichment/src/main/java/org/apache/metron/enrichment/utils/EnrichmentUtils.java
@@ -0,0 +1,80 @@
+/**
+ * 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.metron.enrichment.utils;
+
+import com.google.common.base.Function;
+import com.google.common.base.Joiner;
+import com.google.common.base.Splitter;
+import com.google.common.collect.Iterables;
+import org.apache.metron.hbase.TableProvider;
+import org.apache.metron.enrichment.converter.EnrichmentKey;
+
+import javax.annotation.Nullable;
+import java.lang.reflect.InvocationTargetException;
+
+public class EnrichmentUtils {
+
+ public static final String KEY_PREFIX = "enrichments";
+
+ public static String getEnrichmentKey(String enrichmentName, String field) {
+ return Joiner.on(".").join(new String[]{KEY_PREFIX, enrichmentName, field});
+ }
+
+ public static class TypeToKey implements Function<String, EnrichmentKey> {
+ private final String indicator;
+
+ public TypeToKey(String indicator) {
+ this.indicator = indicator;
+
+ }
+ @Nullable
+ @Override
+ public EnrichmentKey apply(@Nullable String enrichmentType) {
+ return new EnrichmentKey(enrichmentType, indicator);
+ }
+ }
+ public static String toTopLevelField(String field) {
+ if(field == null) {
+ return null;
+ }
+ return Iterables.getLast(Splitter.on('.').split(field));
+ }
+
+ public static TableProvider getTableProvider(String connectorImpl, TableProvider defaultImpl) {
+ if(connectorImpl == null || connectorImpl.length() == 0 || connectorImpl.charAt(0) == '$') {
+ return defaultImpl;
+ }
+ else {
+ try {
+ Class<? extends TableProvider> clazz = (Class<? extends TableProvider>) Class.forName(connectorImpl);
+ return clazz.getConstructor().newInstance();
+ } catch (InstantiationException e) {
+ throw new IllegalStateException("Unable to instantiate connector.", e);
+ } catch (IllegalAccessException e) {
+ throw new IllegalStateException("Unable to instantiate connector: illegal access", e);
+ } catch (InvocationTargetException e) {
+ throw new IllegalStateException("Unable to instantiate connector", e);
+ } catch (NoSuchMethodException e) {
+ throw new IllegalStateException("Unable to instantiate connector: no such method", e);
+ } catch (ClassNotFoundException e) {
+ throw new IllegalStateException("Unable to instantiate connector: class not found", e);
+ }
+ }
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/incubator-metron/blob/0117987e/metron-platform/metron-enrichment/src/main/java/org/apache/metron/enrichment/utils/ThreatIntelUtils.java
----------------------------------------------------------------------
diff --git a/metron-platform/metron-enrichment/src/main/java/org/apache/metron/enrichment/utils/ThreatIntelUtils.java b/metron-platform/metron-enrichment/src/main/java/org/apache/metron/enrichment/utils/ThreatIntelUtils.java
new file mode 100644
index 0000000..7898ccd
--- /dev/null
+++ b/metron-platform/metron-enrichment/src/main/java/org/apache/metron/enrichment/utils/ThreatIntelUtils.java
@@ -0,0 +1,32 @@
+/**
+ * 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.metron.enrichment.utils;
+
+import com.google.common.base.Joiner;
+
+public class ThreatIntelUtils {
+
+ public static final String KEY_PREFIX = "threatintels";
+
+ public static String getThreatIntelKey(String threatIntelName, String field) {
+ return Joiner.on(".").join(new String[]{KEY_PREFIX, threatIntelName, field});
+ }
+
+
+
+}
http://git-wip-us.apache.org/repos/asf/incubator-metron/blob/0117987e/metron-platform/metron-enrichment/src/main/java/org/apache/metron/writer/hdfs/HdfsWriter.java
----------------------------------------------------------------------
diff --git a/metron-platform/metron-enrichment/src/main/java/org/apache/metron/writer/hdfs/HdfsWriter.java b/metron-platform/metron-enrichment/src/main/java/org/apache/metron/writer/hdfs/HdfsWriter.java
new file mode 100644
index 0000000..a364419
--- /dev/null
+++ b/metron-platform/metron-enrichment/src/main/java/org/apache/metron/writer/hdfs/HdfsWriter.java
@@ -0,0 +1,94 @@
+/**
+ * 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.metron.writer.hdfs;
+
+import backtype.storm.tuple.Tuple;
+import org.apache.metron.common.configuration.Configurations;
+import org.apache.metron.common.interfaces.BulkMessageWriter;
+import org.apache.storm.hdfs.bolt.format.FileNameFormat;
+import org.apache.storm.hdfs.bolt.rotation.FileRotationPolicy;
+import org.apache.storm.hdfs.bolt.rotation.NoRotationPolicy;
+import org.apache.storm.hdfs.bolt.sync.CountSyncPolicy;
+import org.apache.storm.hdfs.bolt.sync.SyncPolicy;
+import org.apache.storm.hdfs.common.rotation.RotationAction;
+import org.json.simple.JSONObject;
+
+import java.io.IOException;
+import java.io.Serializable;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+public class HdfsWriter implements BulkMessageWriter<JSONObject>, Serializable {
+ List<RotationAction> rotationActions = new ArrayList<>();
+ FileRotationPolicy rotationPolicy = new NoRotationPolicy();
+ SyncPolicy syncPolicy = new CountSyncPolicy(1); //sync every time, duh.
+ FileNameFormat fileNameFormat;
+ Map<String, SourceHandler> sourceHandlerMap = new HashMap<>();
+ transient Map stormConfig;
+ public HdfsWriter withFileNameFormat(FileNameFormat fileNameFormat){
+ this.fileNameFormat = fileNameFormat;
+ return this;
+ }
+
+ public HdfsWriter withSyncPolicy(SyncPolicy syncPolicy){
+ this.syncPolicy = syncPolicy;
+ return this;
+ }
+ public HdfsWriter withRotationPolicy(FileRotationPolicy rotationPolicy){
+ this.rotationPolicy = rotationPolicy;
+ return this;
+ }
+
+ public HdfsWriter addRotationAction(RotationAction action){
+ this.rotationActions.add(action);
+ return this;
+ }
+
+ @Override
+ public void init(Map stormConfig, Configurations configurations) {
+ this.stormConfig = stormConfig;
+ }
+
+ @Override
+ public void write( String sourceType
+ , Configurations configurations
+ , List<Tuple> tuples
+ , List<JSONObject> messages
+ ) throws Exception
+ {
+ SourceHandler handler = getSourceHandler(sourceType);
+ handler.handle(messages);
+ }
+
+ @Override
+ public void close() {
+ for(SourceHandler handler : sourceHandlerMap.values()) {
+ handler.close();
+ }
+ }
+ private synchronized SourceHandler getSourceHandler(String sourceType) throws IOException {
+ SourceHandler ret = sourceHandlerMap.get(sourceType);
+ if(ret == null) {
+ ret = new SourceHandler(rotationActions, rotationPolicy, syncPolicy, new SourceFileNameFormat(sourceType, fileNameFormat), stormConfig);
+ sourceHandlerMap.put(sourceType, ret);
+ }
+ return ret;
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-metron/blob/0117987e/metron-platform/metron-enrichment/src/main/java/org/apache/metron/writer/hdfs/SourceAwareMoveAction.java
----------------------------------------------------------------------
diff --git a/metron-platform/metron-enrichment/src/main/java/org/apache/metron/writer/hdfs/SourceAwareMoveAction.java b/metron-platform/metron-enrichment/src/main/java/org/apache/metron/writer/hdfs/SourceAwareMoveAction.java
new file mode 100644
index 0000000..1c345b4
--- /dev/null
+++ b/metron-platform/metron-enrichment/src/main/java/org/apache/metron/writer/hdfs/SourceAwareMoveAction.java
@@ -0,0 +1,48 @@
+/**
+ * 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.metron.writer.hdfs;
+
+import org.apache.hadoop.fs.FileSystem;
+import org.apache.hadoop.fs.Path;
+import org.apache.log4j.Logger;
+import org.apache.storm.hdfs.common.rotation.RotationAction;
+
+import java.io.IOException;
+
+public class SourceAwareMoveAction implements RotationAction{
+ private static final Logger LOG = Logger.getLogger(SourceHandler.class);
+ private String destination;
+
+ public SourceAwareMoveAction toDestination(String destDir){
+ destination = destDir;
+ return this;
+ }
+
+ private static String getSource(Path filePath) {
+ return filePath.getParent().getName();
+ }
+
+ @Override
+ public void execute(FileSystem fileSystem, Path filePath) throws IOException {
+ Path destPath = new Path(new Path(destination, getSource(filePath)), filePath.getName());
+ LOG.info("Moving file " + filePath + " to " + destPath);
+ boolean success = fileSystem.rename(filePath, destPath);
+ return;
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-metron/blob/0117987e/metron-platform/metron-enrichment/src/main/java/org/apache/metron/writer/hdfs/SourceFileNameFormat.java
----------------------------------------------------------------------
diff --git a/metron-platform/metron-enrichment/src/main/java/org/apache/metron/writer/hdfs/SourceFileNameFormat.java b/metron-platform/metron-enrichment/src/main/java/org/apache/metron/writer/hdfs/SourceFileNameFormat.java
new file mode 100644
index 0000000..ae0242d
--- /dev/null
+++ b/metron-platform/metron-enrichment/src/main/java/org/apache/metron/writer/hdfs/SourceFileNameFormat.java
@@ -0,0 +1,48 @@
+/**
+ * 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.metron.writer.hdfs;
+
+import backtype.storm.task.TopologyContext;
+import org.apache.storm.hdfs.bolt.format.FileNameFormat;
+
+import java.util.Map;
+
+public class SourceFileNameFormat implements FileNameFormat {
+ FileNameFormat delegate;
+ String sourceType;
+ public SourceFileNameFormat(String sourceType, FileNameFormat delegate) {
+ this.delegate = delegate;
+ this.sourceType = sourceType;
+ }
+
+ @Override
+ public void prepare(Map map, TopologyContext topologyContext) {
+ this.delegate.prepare(map, topologyContext);
+ }
+
+ @Override
+ public String getName(long l, long l1) {
+ return delegate.getName(l, l1);
+ }
+
+ @Override
+ public String getPath() {
+ return delegate.getPath() + "/" + sourceType;
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-metron/blob/0117987e/metron-platform/metron-enrichment/src/main/java/org/apache/metron/writer/hdfs/SourceHandler.java
----------------------------------------------------------------------
diff --git a/metron-platform/metron-enrichment/src/main/java/org/apache/metron/writer/hdfs/SourceHandler.java b/metron-platform/metron-enrichment/src/main/java/org/apache/metron/writer/hdfs/SourceHandler.java
new file mode 100644
index 0000000..0225137
--- /dev/null
+++ b/metron-platform/metron-enrichment/src/main/java/org/apache/metron/writer/hdfs/SourceHandler.java
@@ -0,0 +1,160 @@
+/**
+ * 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.metron.writer.hdfs;
+
+import org.apache.hadoop.conf.Configuration;
+import org.apache.hadoop.fs.FSDataOutputStream;
+import org.apache.hadoop.fs.FileSystem;
+import org.apache.hadoop.fs.LocalFileSystem;
+import org.apache.hadoop.fs.Path;
+import org.apache.hadoop.hdfs.client.HdfsDataOutputStream;
+import org.apache.hadoop.hdfs.util.MD5FileUtils;
+import org.apache.hadoop.io.MD5Hash;
+import org.apache.log4j.Logger;
+import org.apache.storm.hdfs.bolt.format.FileNameFormat;
+import org.apache.storm.hdfs.bolt.rotation.FileRotationPolicy;
+import org.apache.storm.hdfs.bolt.rotation.TimedRotationPolicy;
+import org.apache.storm.hdfs.bolt.sync.SyncPolicy;
+import org.apache.storm.hdfs.common.rotation.RotationAction;
+import org.apache.storm.hdfs.common.security.HdfsSecurityUtil;
+import org.json.simple.JSONObject;
+
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.util.*;
+
+public class SourceHandler {
+ private static final Logger LOG = Logger.getLogger(SourceHandler.class);
+ List<RotationAction> rotationActions = new ArrayList<>();
+ FileRotationPolicy rotationPolicy;
+ SyncPolicy syncPolicy;
+ FileNameFormat fileNameFormat;
+ private long offset = 0;
+ private int rotation = 0;
+ private transient FSDataOutputStream out;
+ private transient Object writeLock;
+ protected transient Timer rotationTimer; // only used for TimedRotationPolicy
+ protected transient FileSystem fs;
+ protected transient Path currentFile;
+ public SourceHandler(List<RotationAction> rotationActions
+ , FileRotationPolicy rotationPolicy
+ , SyncPolicy syncPolicy
+ , FileNameFormat fileNameFormat
+ , Map config
+ ) throws IOException {
+ this.rotationActions = rotationActions;
+ this.rotationPolicy = rotationPolicy;
+ this.syncPolicy = syncPolicy;
+ this.fileNameFormat = fileNameFormat;
+ initialize(config);
+ }
+
+ public void handle(List<JSONObject> messages) throws Exception{
+
+ for(JSONObject message : messages) {
+ byte[] bytes = (message.toJSONString() + "\n").getBytes();
+ synchronized (this.writeLock) {
+ out.write(bytes);
+ this.offset += bytes.length;
+
+ if (this.syncPolicy.mark(null, this.offset)) {
+ if (this.out instanceof HdfsDataOutputStream) {
+ ((HdfsDataOutputStream) this.out).hsync(EnumSet.of(HdfsDataOutputStream.SyncFlag.UPDATE_LENGTH));
+ } else {
+ this.out.hsync();
+ }
+ this.syncPolicy.reset();
+ }
+ }
+
+ if (this.rotationPolicy.mark(null, this.offset)) {
+ rotateOutputFile(); // synchronized
+ this.offset = 0;
+ this.rotationPolicy.reset();
+ }
+ }
+ }
+
+ private void initialize(Map config) throws IOException {
+ this.writeLock = new Object();
+ Configuration hdfsConfig = new Configuration();
+ this.fs = FileSystem.get(new Configuration());
+ HdfsSecurityUtil.login(config, hdfsConfig);
+ this.currentFile = createOutputFile();
+ if(this.rotationPolicy instanceof TimedRotationPolicy){
+ long interval = ((TimedRotationPolicy)this.rotationPolicy).getInterval();
+ this.rotationTimer = new Timer(true);
+ TimerTask task = new TimerTask() {
+ @Override
+ public void run() {
+ try {
+ rotateOutputFile();
+ } catch(IOException e){
+ LOG.warn("IOException during scheduled file rotation.", e);
+ }
+ }
+ };
+ this.rotationTimer.scheduleAtFixedRate(task, interval, interval);
+ }
+ }
+
+ protected void rotateOutputFile() throws IOException {
+ LOG.info("Rotating output file...");
+ long start = System.currentTimeMillis();
+ synchronized (this.writeLock) {
+ closeOutputFile();
+ this.rotation++;
+
+ Path newFile = createOutputFile();
+ LOG.info("Performing " + this.rotationActions.size() + " file rotation actions." );
+ for (RotationAction action : this.rotationActions) {
+ action.execute(this.fs, this.currentFile);
+ }
+ this.currentFile = newFile;
+ }
+ long time = System.currentTimeMillis() - start;
+ LOG.info("File rotation took " + time + " ms.");
+ }
+
+ private Path createOutputFile() throws IOException {
+ Path path = new Path(this.fileNameFormat.getPath(), this.fileNameFormat.getName(this.rotation, System.currentTimeMillis()));
+ if(fs.getScheme().equals("file")) {
+ //in the situation where we're running this in a local filesystem, flushing doesn't work.
+ fs.mkdirs(path.getParent());
+ this.out = new FSDataOutputStream(new FileOutputStream(path.toString()), null);
+ }
+ else {
+ this.out = this.fs.create(path);
+ }
+ return path;
+ }
+
+ private void closeOutputFile() throws IOException {
+ this.out.close();
+ }
+
+
+ public void close() {
+ try {
+ closeOutputFile();
+ } catch (IOException e) {
+ throw new RuntimeException("Unable to close output file.", e);
+ }
+ }
+}