You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@metron.apache.org by ce...@apache.org on 2016/04/29 18:28:33 UTC
[3/6] incubator-metron git commit: METRON-119 - Move PCAP
infrastructure from HBase closes apache/incubator-metron#93
http://git-wip-us.apache.org/repos/asf/incubator-metron/blob/28c250d1/metron-platform/metron-integration-test/pom.xml
----------------------------------------------------------------------
diff --git a/metron-platform/metron-integration-test/pom.xml b/metron-platform/metron-integration-test/pom.xml
index b3c3f09..c55b369 100644
--- a/metron-platform/metron-integration-test/pom.xml
+++ b/metron-platform/metron-integration-test/pom.xml
@@ -97,6 +97,50 @@
</exclusion>
</exclusions>
</dependency>
+
+ <dependency>
+ <groupId>org.apache.hadoop</groupId>
+ <artifactId>hadoop-hdfs</artifactId>
+ <version>${global_hadoop_version}</version>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.hadoop</groupId>
+ <artifactId>hadoop-mapreduce-client-common</artifactId>
+ <version>${global_hadoop_version}</version>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.hadoop</groupId>
+ <artifactId>hadoop-auth</artifactId>
+ <version>${global_hadoop_version}</version>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.hadoop</groupId>
+ <artifactId>hadoop-mapreduce-client-core</artifactId>
+ <version>${global_hadoop_version}</version>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.hadoop</groupId>
+ <artifactId>hadoop-common</artifactId>
+ <classifier>tests</classifier>
+ <version>${global_hadoop_version}</version>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.hadoop</groupId>
+ <artifactId>hadoop-hdfs</artifactId>
+ <classifier>tests</classifier>
+ <version>${global_hadoop_version}</version>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.hadoop</groupId>
+ <artifactId>hadoop-mapreduce-client-jobclient</artifactId>
+ <classifier>tests</classifier>
+ <version>${global_hadoop_version}</version>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.hadoop</groupId>
+ <artifactId>hadoop-mapreduce-client-jobclient</artifactId>
+ <version>${global_hadoop_version}</version>
+ </dependency>
<dependency>
<groupId>org.apache.metron</groupId>
<artifactId>metron-enrichment</artifactId>
@@ -113,7 +157,6 @@
<version>0.1BETA</version>
</dependency>
</dependencies>
-
<build>
</build>
<reporting>
http://git-wip-us.apache.org/repos/asf/incubator-metron/blob/28c250d1/metron-platform/metron-integration-test/src/main/java/org/apache/metron/integration/ComponentRunner.java
----------------------------------------------------------------------
diff --git a/metron-platform/metron-integration-test/src/main/java/org/apache/metron/integration/ComponentRunner.java b/metron-platform/metron-integration-test/src/main/java/org/apache/metron/integration/ComponentRunner.java
index c938741..d78fd97 100644
--- a/metron-platform/metron-integration-test/src/main/java/org/apache/metron/integration/ComponentRunner.java
+++ b/metron-platform/metron-integration-test/src/main/java/org/apache/metron/integration/ComponentRunner.java
@@ -127,7 +127,7 @@ public class ComponentRunner {
long start = System.currentTimeMillis();
while(true) {
long duration = System.currentTimeMillis() - start;
- if(duration > maxTimeMS) {
+ if(maxTimeMS > 0 && duration > maxTimeMS) {
throw new RuntimeException("Took too long to complete: " + duration + " > " + maxTimeMS);
}
ReadinessState state = successState.process(this);
http://git-wip-us.apache.org/repos/asf/incubator-metron/blob/28c250d1/metron-platform/metron-integration-test/src/main/java/org/apache/metron/integration/components/FluxTopologyComponent.java
----------------------------------------------------------------------
diff --git a/metron-platform/metron-integration-test/src/main/java/org/apache/metron/integration/components/FluxTopologyComponent.java b/metron-platform/metron-integration-test/src/main/java/org/apache/metron/integration/components/FluxTopologyComponent.java
index 3bb0c56..442e47c 100644
--- a/metron-platform/metron-integration-test/src/main/java/org/apache/metron/integration/components/FluxTopologyComponent.java
+++ b/metron-platform/metron-integration-test/src/main/java/org/apache/metron/integration/components/FluxTopologyComponent.java
@@ -85,6 +85,9 @@ public class FluxTopologyComponent implements InMemoryComponent {
return topologyProperties;
}
+ public String getZookeeperConnectString() {
+ return "localhost:2000";
+ }
public void start() throws UnableToStartException{
try {
stormCluster = new LocalCluster();
http://git-wip-us.apache.org/repos/asf/incubator-metron/blob/28c250d1/metron-platform/metron-integration-test/src/main/java/org/apache/metron/integration/components/KafkaWithZKComponent.java
----------------------------------------------------------------------
diff --git a/metron-platform/metron-integration-test/src/main/java/org/apache/metron/integration/components/KafkaWithZKComponent.java b/metron-platform/metron-integration-test/src/main/java/org/apache/metron/integration/components/KafkaWithZKComponent.java
index fb7bcde..42d7567 100644
--- a/metron-platform/metron-integration-test/src/main/java/org/apache/metron/integration/components/KafkaWithZKComponent.java
+++ b/metron-platform/metron-integration-test/src/main/java/org/apache/metron/integration/components/KafkaWithZKComponent.java
@@ -100,12 +100,15 @@ public class KafkaWithZKComponent implements InMemoryComponent {
return "localhost:" + brokerPort;
}
+ public <K,V> KafkaProducer<K, V> createProducer(Class<K> keyClass, Class<V> valueClass) {
+ return createProducer(new HashMap<>(), keyClass, valueClass);
+ }
public KafkaProducer<String, byte[]> createProducer()
{
- return createProducer(new HashMap<String, Object>());
+ return createProducer(String.class, byte[].class);
}
- public KafkaProducer<String, byte[]> createProducer(Map<String, Object> properties)
+ public <K,V> KafkaProducer<K,V> createProducer(Map<String, Object> properties, Class<K> keyClass, Class<V> valueClass)
{
Map<String, Object> producerConfig = new HashMap<>();
producerConfig.put("bootstrap.servers", getBrokerList());
@@ -222,4 +225,4 @@ public class KafkaWithZKComponent implements InMemoryComponent {
}
kafkaProducer.close();
}
-}
\ No newline at end of file
+}
http://git-wip-us.apache.org/repos/asf/incubator-metron/blob/28c250d1/metron-platform/metron-integration-test/src/main/java/org/apache/metron/integration/components/MRComponent.java
----------------------------------------------------------------------
diff --git a/metron-platform/metron-integration-test/src/main/java/org/apache/metron/integration/components/MRComponent.java b/metron-platform/metron-integration-test/src/main/java/org/apache/metron/integration/components/MRComponent.java
new file mode 100644
index 0000000..d182906
--- /dev/null
+++ b/metron-platform/metron-integration-test/src/main/java/org/apache/metron/integration/components/MRComponent.java
@@ -0,0 +1,68 @@
+/**
+ * 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.integration.components;
+
+import org.apache.hadoop.conf.Configuration;
+import org.apache.hadoop.fs.Path;
+import org.apache.hadoop.hdfs.MiniDFSCluster;
+import org.apache.hadoop.yarn.conf.YarnConfiguration;
+import org.apache.metron.integration.InMemoryComponent;
+
+import java.io.IOException;
+
+public class MRComponent implements InMemoryComponent {
+ private Configuration configuration;
+ MiniDFSCluster cluster;
+ private Path basePath;
+
+ public MRComponent withBasePath(String path) {
+ basePath = new Path(path);
+ return this;
+ }
+
+ public Configuration getConfiguration() {
+ return configuration;
+ }
+
+ public Path getBasePath() {
+ return basePath;
+ }
+
+ @Override
+ public void start() {
+ configuration = new Configuration();
+ System.clearProperty(MiniDFSCluster.PROP_TEST_BUILD_DATA);
+ configuration.set(YarnConfiguration.YARN_MINICLUSTER_FIXED_PORTS, "true");
+ if(basePath == null) {
+ throw new RuntimeException("Unable to start cluster: You must specify the basepath");
+ }
+ configuration.set(MiniDFSCluster.HDFS_MINIDFS_BASEDIR, basePath.toString());
+ try {
+ cluster = new MiniDFSCluster.Builder(configuration)
+ .build();
+ } catch (IOException e) {
+ throw new RuntimeException("Unable to start cluster", e);
+ }
+ }
+
+ @Override
+ public void stop() {
+ cluster.shutdown();
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-metron/blob/28c250d1/metron-platform/metron-integration-test/src/main/java/org/apache/metron/integration/utils/KafkaUtil.java
----------------------------------------------------------------------
diff --git a/metron-platform/metron-integration-test/src/main/java/org/apache/metron/integration/utils/KafkaUtil.java b/metron-platform/metron-integration-test/src/main/java/org/apache/metron/integration/utils/KafkaUtil.java
index e3a3110..0292808 100644
--- a/metron-platform/metron-integration-test/src/main/java/org/apache/metron/integration/utils/KafkaUtil.java
+++ b/metron-platform/metron-integration-test/src/main/java/org/apache/metron/integration/utils/KafkaUtil.java
@@ -18,24 +18,24 @@
package org.apache.metron.integration.utils;
-import kafka.consumer.ConsumerIterator;
-import kafka.consumer.KafkaStream;
-import kafka.javaapi.producer.Producer;
-import kafka.producer.KeyedMessage;
+import org.apache.kafka.clients.producer.Producer;
+import org.apache.kafka.clients.producer.ProducerRecord;
-import java.util.HashMap;
-import java.util.List;
import java.util.Map;
public class KafkaUtil {
- public static <K,V> void send(Producer<K,V> producer, K key, V value, String topic) {
- producer.send(new KeyedMessage<>(topic, key,value));
- }
+ public static <K,V> void send(Producer<K,V> producer, K key, V value, String topic) {
+ ProducerRecord<K,V> record = new ProducerRecord<K, V>(topic, key, value);
+ producer.send(record);
+ }
- public static <K,V> void send(Producer<K,V> producer, Iterable<Map.Entry<K,V>> messages, String topic) {
- for(Map.Entry<K,V> kv : messages) {
- send(producer, kv.getKey(), kv.getValue(), topic);
+ public static <K,V> void send(Producer<K,V> producer, Iterable<Map.Entry<K,V>> messages, String topic, long sleepBetween) throws InterruptedException {
+ for(Map.Entry<K,V> kv : messages) {
+ send(producer, kv.getKey(), kv.getValue(), topic);
+ if(sleepBetween > 0) {
+ Thread.sleep(sleepBetween);
+ }
+ }
}
- }
-}
\ No newline at end of file
+}
http://git-wip-us.apache.org/repos/asf/incubator-metron/blob/28c250d1/metron-platform/metron-parsers/src/main/assembly/assembly.xml
----------------------------------------------------------------------
diff --git a/metron-platform/metron-parsers/src/main/assembly/assembly.xml b/metron-platform/metron-parsers/src/main/assembly/assembly.xml
index d6da96c..abed0af 100644
--- a/metron-platform/metron-parsers/src/main/assembly/assembly.xml
+++ b/metron-platform/metron-parsers/src/main/assembly/assembly.xml
@@ -28,6 +28,7 @@
</excludes>
<fileMode>0644</fileMode>
<lineEnding>unix</lineEnding>
+ <filtered>true</filtered>
</fileSet>
<fileSet>
<directory>${project.basedir}/src/main/flux</directory>
@@ -53,14 +54,15 @@
</fileSet>
<fileSet>
<directory>${project.basedir}/src/main/scripts</directory>
- <outputDirectory>/scripts</outputDirectory>
+ <outputDirectory>/bin</outputDirectory>
<useDefaultExcludes>true</useDefaultExcludes>
<excludes>
<exclude>**/*.formatted</exclude>
<exclude>**/*.filtered</exclude>
</excludes>
- <fileMode>0644</fileMode>
+ <fileMode>0755</fileMode>
<lineEnding>unix</lineEnding>
+ <filtered>true</filtered>
</fileSet>
<fileSet>
<directory>${project.basedir}/target</directory>
http://git-wip-us.apache.org/repos/asf/incubator-metron/blob/28c250d1/metron-platform/metron-parsers/src/main/flux/pcap/remote.yaml
----------------------------------------------------------------------
diff --git a/metron-platform/metron-parsers/src/main/flux/pcap/remote.yaml b/metron-platform/metron-parsers/src/main/flux/pcap/remote.yaml
deleted file mode 100644
index 418fac1..0000000
--- a/metron-platform/metron-parsers/src/main/flux/pcap/remote.yaml
+++ /dev/null
@@ -1,70 +0,0 @@
-# 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.
-
-name: "pcap"
-config:
- topology.workers: 1
-
-components:
- - id: "parser"
- className: "org.apache.metron.parsers.pcap.PcapParser"
- - id: "writer"
- className: "org.apache.metron.pcap.writer.PcapWriter"
- constructorArgs:
- - "${bolt.hbase.table.name}"
- - "${bolt.hbase.table.fields}"
- - id: "zkHosts"
- className: "storm.kafka.ZkHosts"
- constructorArgs:
- - "${kafka.zk}"
- - id: "kafkaConfig"
- className: "storm.kafka.SpoutConfig"
- constructorArgs:
- # zookeeper hosts
- - ref: "zkHosts"
- # topic name
- - "pcap"
- # zk root
- - ""
- # id
- - "pcap"
- properties:
- - name: "ignoreZkOffsets"
- value: true
- - name: "startOffsetTime"
- value: -1
-
-spouts:
- - id: "kafkaSpout"
- className: "storm.kafka.KafkaSpout"
- constructorArgs:
- - ref: "kafkaConfig"
-
-bolts:
- - id: "parserBolt"
- className: "org.apache.metron.parsers.bolt.ParserBolt"
- constructorArgs:
- - "${kafka.zk}"
- - "pcap"
- - ref: "parser"
- - ref: "writer"
-
-streams:
- - name: "spout -> bolt"
- from: "kafkaSpout"
- to: "parserBolt"
- grouping:
- type: SHUFFLE
http://git-wip-us.apache.org/repos/asf/incubator-metron/blob/28c250d1/metron-platform/metron-parsers/src/main/flux/pcap/test.yaml
----------------------------------------------------------------------
diff --git a/metron-platform/metron-parsers/src/main/flux/pcap/test.yaml b/metron-platform/metron-parsers/src/main/flux/pcap/test.yaml
deleted file mode 100644
index f5c5011..0000000
--- a/metron-platform/metron-parsers/src/main/flux/pcap/test.yaml
+++ /dev/null
@@ -1,74 +0,0 @@
-# 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.
-
-name: "pcap-test"
-config:
- topology.workers: 1
-
-components:
- - id: "parser"
- className: "org.apache.metron.parsers.pcap.PcapParser"
- - id: "writer"
- className: "org.apache.metron.pcap.writer.PcapWriter"
- constructorArgs:
- - "${bolt.hbase.table.name}"
- - "${bolt.hbase.table.fields}"
- configMethods:
- - name: "withProviderImpl"
- args:
- - "${hbase.provider.impl}"
- - id: "zkHosts"
- className: "storm.kafka.ZkHosts"
- constructorArgs:
- - "${kafka.zk}"
- - id: "kafkaConfig"
- className: "storm.kafka.SpoutConfig"
- constructorArgs:
- # zookeeper hosts
- - ref: "zkHosts"
- # topic name
- - "pcap"
- # zk root
- - ""
- # id
- - "pcap"
- properties:
- - name: "ignoreZkOffsets"
- value: false
- - name: "startOffsetTime"
- value: -2
-
-spouts:
- - id: "kafkaSpout"
- className: "storm.kafka.KafkaSpout"
- constructorArgs:
- - ref: "kafkaConfig"
-
-bolts:
- - id: "parserBolt"
- className: "org.apache.metron.parsers.bolt.ParserBolt"
- constructorArgs:
- - "${kafka.zk}"
- - "pcap"
- - ref: "parser"
- - ref: "writer"
-
-streams:
- - name: "spout -> bolt"
- from: "kafkaSpout"
- to: "parserBolt"
- grouping:
- type: SHUFFLE
http://git-wip-us.apache.org/repos/asf/incubator-metron/blob/28c250d1/metron-platform/metron-parsers/src/main/java/org/apache/metron/parsers/GrokParser.java
----------------------------------------------------------------------
diff --git a/metron-platform/metron-parsers/src/main/java/org/apache/metron/parsers/GrokParser.java b/metron-platform/metron-parsers/src/main/java/org/apache/metron/parsers/GrokParser.java
index 82734a2..6ebc36b 100644
--- a/metron-platform/metron-parsers/src/main/java/org/apache/metron/parsers/GrokParser.java
+++ b/metron-platform/metron-parsers/src/main/java/org/apache/metron/parsers/GrokParser.java
@@ -22,6 +22,7 @@ import oi.thekraken.grok.api.Match;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
+import org.apache.metron.common.Constants;
import org.apache.metron.parsers.interfaces.MessageParser;
import org.json.simple.JSONObject;
import org.slf4j.Logger;
@@ -133,7 +134,7 @@ public class GrokParser implements MessageParser<JSONObject>, Serializable {
}
}
if (timestampField != null) {
- message.put("timestamp", message.get(timestampField));
+ message.put(Constants.Fields.TIMESTAMP.getName(), message.get(timestampField));
}
message.remove(patternLabel);
messages.add(message);
@@ -146,7 +147,7 @@ public class GrokParser implements MessageParser<JSONObject>, Serializable {
@Override
public boolean validate(JSONObject message) {
- Object timestampObject = message.get("timestamp");
+ Object timestampObject = message.get(Constants.Fields.TIMESTAMP.getName());
if (timestampObject instanceof Long) {
Long timestamp = (Long) timestampObject;
if (timestamp > 0) {
http://git-wip-us.apache.org/repos/asf/incubator-metron/blob/28c250d1/metron-platform/metron-parsers/src/main/java/org/apache/metron/parsers/bro/BasicBroParser.java
----------------------------------------------------------------------
diff --git a/metron-platform/metron-parsers/src/main/java/org/apache/metron/parsers/bro/BasicBroParser.java b/metron-platform/metron-parsers/src/main/java/org/apache/metron/parsers/bro/BasicBroParser.java
index 71eb64f..74ea082 100644
--- a/metron-platform/metron-parsers/src/main/java/org/apache/metron/parsers/bro/BasicBroParser.java
+++ b/metron-platform/metron-parsers/src/main/java/org/apache/metron/parsers/bro/BasicBroParser.java
@@ -18,6 +18,7 @@
package org.apache.metron.parsers.bro;
+import org.apache.metron.common.Constants;
import org.apache.metron.parsers.BasicParser;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
@@ -85,38 +86,38 @@ public class BasicBroParser extends BasicParser {
}
payload.put("original_string", originalString);
- replaceKey(payload, "timestamp", new String[]{ "ts" });
+ replaceKey(payload, Constants.Fields.TIMESTAMP.getName(), new String[]{ "ts" });
long timestamp = 0L;
- if (payload.containsKey("timestamp")) {
+ if (payload.containsKey(Constants.Fields.TIMESTAMP.getName())) {
try {
- String broTimestamp = payload.get("timestamp").toString();
+ String broTimestamp = payload.get(Constants.Fields.TIMESTAMP.getName()).toString();
String convertedTimestamp = broTimestamp.replace(".","");
convertedTimestamp = convertedTimestamp.substring(0,13);
timestamp = Long.parseLong(convertedTimestamp);
- payload.put("timestamp", timestamp);
+ payload.put(Constants.Fields.TIMESTAMP.getName(), timestamp);
payload.put("bro_timestamp",broTimestamp);
- _LOG.trace(String.format("[Metron] new bro record - timestamp : %s", payload.get("timestamp")));
+ _LOG.trace(String.format("[Metron] new bro record - timestamp : %s", payload.get(Constants.Fields.TIMESTAMP.getName())));
} catch (NumberFormatException nfe) {
_LOG.error(String.format("[Metron] timestamp is invalid: %s", payload.get("timestamp")));
- payload.put("timestamp", 0);
+ payload.put(Constants.Fields.TIMESTAMP.getName(), 0);
}
}
- boolean ipSrcReplaced = replaceKey(payload, "ip_src_addr", new String[]{"source_ip", "id.orig_h"});
+ boolean ipSrcReplaced = replaceKey(payload, Constants.Fields.SRC_ADDR.getName(), new String[]{"source_ip", "id.orig_h"});
if (!ipSrcReplaced) {
- replaceKeyArray(payload, "ip_src_addr", new String[]{ "tx_hosts" });
+ replaceKeyArray(payload, Constants.Fields.SRC_ADDR.getName(), new String[]{ "tx_hosts" });
}
- boolean ipDstReplaced = replaceKey(payload, "ip_dst_addr", new String[]{"dest_ip", "id.resp_h"});
+ boolean ipDstReplaced = replaceKey(payload, Constants.Fields.DST_ADDR.getName(), new String[]{"dest_ip", "id.resp_h"});
if (!ipDstReplaced) {
- replaceKeyArray(payload, "ip_dst_addr", new String[]{ "rx_hosts" });
+ replaceKeyArray(payload, Constants.Fields.DST_ADDR.getName(), new String[]{ "rx_hosts" });
}
- replaceKey(payload, "ip_src_port", new String[]{"source_port", "id.orig_p"});
- replaceKey(payload, "ip_dst_port", new String[]{"dest_port", "id.resp_p"});
+ replaceKey(payload, Constants.Fields.SRC_PORT.getName(), new String[]{"source_port", "id.orig_p"});
+ replaceKey(payload, Constants.Fields.DST_PORT.getName(), new String[]{"dest_port", "id.resp_p"});
- payload.put("protocol", key);
+ payload.put(Constants.Fields.PROTOCOL.getName(), key);
_LOG.debug("[Metron] Returning parsed message: " + payload);
messages.add(payload);
return messages;
http://git-wip-us.apache.org/repos/asf/incubator-metron/blob/28c250d1/metron-platform/metron-parsers/src/main/java/org/apache/metron/parsers/pcap/PcapParser.java
----------------------------------------------------------------------
diff --git a/metron-platform/metron-parsers/src/main/java/org/apache/metron/parsers/pcap/PcapParser.java b/metron-platform/metron-parsers/src/main/java/org/apache/metron/parsers/pcap/PcapParser.java
deleted file mode 100644
index 899dbd8..0000000
--- a/metron-platform/metron-parsers/src/main/java/org/apache/metron/parsers/pcap/PcapParser.java
+++ /dev/null
@@ -1,229 +0,0 @@
-/**
- * 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.parsers.pcap;
-
-import org.apache.commons.io.FileUtils;
-import org.apache.log4j.Logger;
-import org.apache.metron.parsers.interfaces.MessageParser;
-import org.apache.metron.pcap.Constants;
-import org.apache.metron.pcap.MetronEthernetDecoder;
-import org.apache.metron.pcap.PacketInfo;
-import org.apache.metron.pcap.PcapByteInputStream;
-import org.json.simple.JSONObject;
-import org.json.simple.JSONValue;
-import org.krakenapps.pcap.decoder.ethernet.EthernetDecoder;
-import org.krakenapps.pcap.decoder.ethernet.EthernetType;
-import org.krakenapps.pcap.decoder.ip.IpDecoder;
-import org.krakenapps.pcap.decoder.ip.Ipv4Packet;
-import org.krakenapps.pcap.decoder.tcp.TcpPacket;
-import org.krakenapps.pcap.decoder.udp.UdpPacket;
-import org.krakenapps.pcap.file.GlobalHeader;
-import org.krakenapps.pcap.packet.PacketHeader;
-import org.krakenapps.pcap.packet.PcapPacket;
-import org.krakenapps.pcap.util.Buffer;
-
-import java.io.EOFException;
-import java.io.File;
-import java.io.IOException;
-import java.io.Serializable;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.List;
-
-public class PcapParser implements MessageParser<JSONObject>, Serializable {
-
- private static final Logger LOG = Logger.getLogger(PcapParser.class);
-
- private EthernetDecoder ethernetDecoder;
- private long timePrecisionDivisor = 1L;
-
- public PcapParser withTsPrecision(String tsPrecision) {
- if (tsPrecision.equalsIgnoreCase("MILLI")) {
- //Convert nanos to millis
- LOG.info("Configured for MILLI, setting timePrecisionDivisor to 1000000L" );
- timePrecisionDivisor = 1000000L;
- } else if (tsPrecision.equalsIgnoreCase("MICRO")) {
- //Convert nanos to micro
- LOG.info("Configured for MICRO, setting timePrecisionDivisor to 1000L" );
- timePrecisionDivisor = 1000L;
- } else if (tsPrecision.equalsIgnoreCase("NANO")) {
- //Keep nano as is.
- LOG.info("Configured for NANO, setting timePrecisionDivisor to 1L" );
- timePrecisionDivisor = 1L;
- } else {
- LOG.info("bolt.parser.ts.precision not set. Default to NANO");
- timePrecisionDivisor = 1L;
- }
- return this;
- }
-
- @Override
- public void init() {
- ethernetDecoder = new MetronEthernetDecoder();
- IpDecoder ipDecoder = new IpDecoder();
- ethernetDecoder.register(EthernetType.IPV4, ipDecoder);
- }
-
- @Override
- public List<JSONObject> parse(byte[] pcap) {
- List<JSONObject> messages = new ArrayList<>();
- List<PacketInfo> packetInfoList = new ArrayList<>();
- try {
- packetInfoList = getPacketInfo(pcap);
- } catch (IOException e) {
- e.printStackTrace();
- }
- for (PacketInfo packetInfo : packetInfoList) {
- JSONObject message = (JSONObject) JSONValue.parse(packetInfo.getJsonIndexDoc());
- messages.add(message);
- }
- return messages;
- }
-
- @Override
- public boolean validate(JSONObject message) {
- List<String> requiredFields = Arrays.asList("ip_src_addr",
- "ip_dst_addr",
- "ip_protocol",
- "ip_src_port",
- "ip_dst_port");
- return message.keySet().containsAll(requiredFields);
-
- }
-
- /**
- * Parses the.
- *
- * @param pcap
- * the pcap
- * @return the list * @throws IOException Signals that an I/O exception has
- * occurred. * @throws IOException * @throws IOException * @throws
- * IOException
- * @throws IOException
- * Signals that an I/O exception has occurred.
- */
- public List<PacketInfo> getPacketInfo(byte[] pcap) throws IOException {
- List<PacketInfo> packetInfoList = new ArrayList<PacketInfo>();
-
- PcapByteInputStream pcapByteInputStream = new PcapByteInputStream(pcap);
-
- GlobalHeader globalHeader = pcapByteInputStream.getGlobalHeader();
- while (true) {
- try
-
- {
- PcapPacket packet = pcapByteInputStream.getPacket();
- // int packetCounter = 0;
- // PacketHeader packetHeader = null;
- // Ipv4Packet ipv4Packet = null;
- TcpPacket tcpPacket = null;
- UdpPacket udpPacket = null;
- // Buffer packetDataBuffer = null;
- int sourcePort = 0;
- int destinationPort = 0;
-
- // LOG.trace("Got packet # " + ++packetCounter);
-
- // LOG.trace(packet.getPacketData());
- ethernetDecoder.decode(packet);
-
- PacketHeader packetHeader = packet.getPacketHeader();
- Ipv4Packet ipv4Packet = Ipv4Packet.parse(packet.getPacketData());
-
- if (ipv4Packet.getProtocol() == Constants.PROTOCOL_TCP) {
- tcpPacket = TcpPacket.parse(ipv4Packet);
-
- }
-
- if (ipv4Packet.getProtocol() == Constants.PROTOCOL_UDP) {
-
- Buffer packetDataBuffer = ipv4Packet.getData();
- sourcePort = packetDataBuffer.getUnsignedShort();
- destinationPort = packetDataBuffer.getUnsignedShort();
-
- udpPacket = new UdpPacket(ipv4Packet, sourcePort, destinationPort);
-
- udpPacket.setLength(packetDataBuffer.getUnsignedShort());
- udpPacket.setChecksum(packetDataBuffer.getUnsignedShort());
- packetDataBuffer.discardReadBytes();
- udpPacket.setData(packetDataBuffer);
- }
-
- packetInfoList.add(new PacketInfo(globalHeader, packetHeader, packet,
- ipv4Packet, tcpPacket, udpPacket));
- } catch (NegativeArraySizeException ignored) {
- LOG.debug("Ignorable exception while parsing packet.", ignored);
- } catch (EOFException eof) { // $codepro.audit.disable logExceptions
- // Ignore exception and break
- break;
- }
- }
- return packetInfoList;
- }
-
- /**
- * The main method.
- *
- * @param args
- * the arguments
- * @throws IOException
- * Signals that an I/O exception has occurred.
- * @throws InterruptedException
- * the interrupted exception
- */
- public static void main(String[] args) throws IOException,
- InterruptedException {
-
- double totalIterations = 1000000;
- double parallelism = 64;
- double targetEvents = 1000000;
- PcapParser pcapParser = new PcapParser();
- File fin = new File("/Users/sheetal/Downloads/bad_packets/bad_packet_1405988125427.pcap");
- File fout = new File(fin.getAbsolutePath() + ".parsed");
- byte[] pcapBytes = FileUtils.readFileToByteArray(fin);
- long startTime = System.currentTimeMillis();
- for (int i = 0; i < totalIterations; i++) {
- List<PacketInfo> list = pcapParser.getPacketInfo(pcapBytes);
-
- for (PacketInfo packetInfo : list) {
- System.out.println(packetInfo.getJsonIndexDoc());
- }
- }
- long endTime = System.currentTimeMillis();
-
- System.out.println("Time taken to process " + totalIterations + " events :"
- + (endTime - startTime) + " milliseconds");
-
- System.out
- .println("With parallelism of "
- + parallelism
- + " estimated time to process "
- + targetEvents
- + " events: "
- + (((((endTime - startTime) / totalIterations) * targetEvents) / parallelism) / 1000)
- + " seconds");
- System.out.println("With parallelism of " + parallelism
- + " estimated # of events per second: "
- + ((parallelism * 1000 * totalIterations) / (endTime - startTime))
- + " events");
- System.out.println("Expected Parallelism to process " + targetEvents
- + " events in a second: "
- + (targetEvents / ((1000 * totalIterations) / (endTime - startTime))));
- }
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-metron/blob/28c250d1/metron-platform/metron-parsers/src/main/java/org/apache/metron/parsers/snort/BasicSnortParser.java
----------------------------------------------------------------------
diff --git a/metron-platform/metron-parsers/src/main/java/org/apache/metron/parsers/snort/BasicSnortParser.java b/metron-platform/metron-parsers/src/main/java/org/apache/metron/parsers/snort/BasicSnortParser.java
index 4455e57..a82d8d6 100644
--- a/metron-platform/metron-parsers/src/main/java/org/apache/metron/parsers/snort/BasicSnortParser.java
+++ b/metron-platform/metron-parsers/src/main/java/org/apache/metron/parsers/snort/BasicSnortParser.java
@@ -17,6 +17,7 @@
*/
package org.apache.metron.parsers.snort;
+import org.apache.metron.common.Constants;
import org.apache.metron.parsers.BasicParser;
import org.json.simple.JSONObject;
import org.slf4j.Logger;
@@ -29,135 +30,135 @@ import java.util.*;
@SuppressWarnings("serial")
public class BasicSnortParser extends BasicParser {
- private static final Logger _LOG = LoggerFactory
- .getLogger(BasicSnortParser.class);
-
- /**
- * The default field names for Snort Alerts.
- */
- private String[] fieldNames = new String[] {
- "timestamp",
- "sig_generator",
- "sig_id",
- "sig_rev",
- "msg",
- "protocol",
- "ip_src_addr",
- "ip_src_port",
- "ip_dst_addr",
- "ip_dst_port",
- "ethsrc",
- "ethdst",
- "ethlen",
- "tcpflags",
- "tcpseq",
- "tcpack",
- "tcplen",
- "tcpwindow",
- "ttl",
- "tos",
- "id",
- "dgmlen",
- "iplen",
- "icmptype",
- "icmpcode",
- "icmpid",
- "icmpseq"
- };
-
-
- /**
- * Snort alerts are received as CSV records
- */
- private String recordDelimiter = ",";
-
- @Override
- public void init() {
-
- }
-
- @Override
- public List<JSONObject> parse(byte[] rawMessage) {
-
- JSONObject jsonMessage = new JSONObject();
- List<JSONObject> messages = new ArrayList<>();
- try {
- // snort alerts expected as csv records
- String csvMessage = new String(rawMessage, "UTF-8");
- String[] records = csvMessage.split(recordDelimiter, -1);
-
- // validate the number of fields
- if (records.length != fieldNames.length) {
- throw new IllegalArgumentException("Unexpected number of fields, expected: " + fieldNames.length + " got: " + records.length);
- }
- long timestamp = 0L;
- // build the json record from each field
- for (int i=0; i<records.length; i++) {
-
- String field = fieldNames[i];
- String record = records[i];
-
- if("timestamp".equals(field)) {
-
- // convert the timestamp to epoch
- timestamp = toEpoch(record);
- jsonMessage.put("timestamp", timestamp);
-
- } else {
- jsonMessage.put(field, record);
- }
- }
-
- // add original msg; required by 'checkForSchemaCorrectness'
- jsonMessage.put("original_string", csvMessage);
- jsonMessage.put("is_alert", "true");
- messages.add(jsonMessage);
- } catch (Exception e) {
-
- _LOG.error("unable to parse message: " + rawMessage);
- e.printStackTrace();
- return null;
+ private static final Logger _LOG = LoggerFactory
+ .getLogger(BasicSnortParser.class);
+
+ /**
+ * The default field names for Snort Alerts.
+ */
+ private String[] fieldNames = new String[] {
+ Constants.Fields.TIMESTAMP.getName(),
+ "sig_generator",
+ "sig_id",
+ "sig_rev",
+ "msg",
+ Constants.Fields.PROTOCOL.getName(),
+ Constants.Fields.SRC_ADDR.getName(),
+ Constants.Fields.SRC_PORT.getName(),
+ Constants.Fields.DST_ADDR.getName(),
+ Constants.Fields.DST_PORT.getName(),
+ "ethsrc",
+ "ethdst",
+ "ethlen",
+ "tcpflags",
+ "tcpseq",
+ "tcpack",
+ "tcplen",
+ "tcpwindow",
+ "ttl",
+ "tos",
+ "id",
+ "dgmlen",
+ "iplen",
+ "icmptype",
+ "icmpcode",
+ "icmpid",
+ "icmpseq"
+ };
+
+
+ /**
+ * Snort alerts are received as CSV records
+ */
+ private String recordDelimiter = ",";
+
+ @Override
+ public void init() {
+
+ }
+
+ @Override
+ public List<JSONObject> parse(byte[] rawMessage) {
+
+ JSONObject jsonMessage = new JSONObject();
+ List<JSONObject> messages = new ArrayList<>();
+ try {
+ // snort alerts expected as csv records
+ String csvMessage = new String(rawMessage, "UTF-8");
+ String[] records = csvMessage.split(recordDelimiter, -1);
+
+ // validate the number of fields
+ if (records.length != fieldNames.length) {
+ throw new IllegalArgumentException("Unexpected number of fields, expected: " + fieldNames.length + " got: " + records.length);
+ }
+ long timestamp = 0L;
+ // build the json record from each field
+ for (int i=0; i<records.length; i++) {
+
+ String field = fieldNames[i];
+ String record = records[i];
+
+ if("timestamp".equals(field)) {
+
+ // convert the timestamp to epoch
+ timestamp = toEpoch(record);
+ jsonMessage.put("timestamp", timestamp);
+
+ } else {
+ jsonMessage.put(field, record);
}
-
- return messages;
- }
-
- /**
- * Parses Snort's default date-time representation and
- * converts to epoch.
- * @param snortDatetime Snort's default date-time as String '01/27-16:01:04.877970'
- * @return epoch time
- * @throws java.text.ParseException
- */
- private long toEpoch(String snortDatetime) throws ParseException {
+ }
+
+ // add original msg; required by 'checkForSchemaCorrectness'
+ jsonMessage.put("original_string", csvMessage);
+ jsonMessage.put("is_alert", "true");
+ messages.add(jsonMessage);
+ } catch (Exception e) {
+
+ _LOG.error("unable to parse message: " + rawMessage);
+ e.printStackTrace();
+ return null;
+ }
+
+ return messages;
+ }
+
+ /**
+ * Parses Snort's default date-time representation and
+ * converts to epoch.
+ * @param snortDatetime Snort's default date-time as String '01/27-16:01:04.877970'
+ * @return epoch time
+ * @throws java.text.ParseException
+ */
+ private long toEpoch(String snortDatetime) throws ParseException {
/*
* TODO how does Snort not embed the year in their default timestamp?! need to change this in
* Snort configuration. for now, just assume current year.
*/
- int year = Calendar.getInstance().get(Calendar.YEAR);
- String withYear = Integer.toString(year) + " " + snortDatetime;
-
- // convert to epoch time
- SimpleDateFormat df = new SimpleDateFormat("yyyy MM/dd-HH:mm:ss.S");
- Date date = df.parse(withYear);
- return date.getTime();
- }
-
- public String getRecordDelimiter() {
- return this.recordDelimiter;
- }
-
- public void setRecordDelimiter(String recordDelimiter) {
- this.recordDelimiter = recordDelimiter;
- }
-
- public String[] getFieldNames() {
- return this.fieldNames;
- }
-
- public void setFieldNames(String[] fieldNames) {
- this.fieldNames = fieldNames;
- }
+ int year = Calendar.getInstance().get(Calendar.YEAR);
+ String withYear = Integer.toString(year) + " " + snortDatetime;
+
+ // convert to epoch time
+ SimpleDateFormat df = new SimpleDateFormat("yyyy MM/dd-HH:mm:ss.S");
+ Date date = df.parse(withYear);
+ return date.getTime();
+ }
+
+ public String getRecordDelimiter() {
+ return this.recordDelimiter;
+ }
+
+ public void setRecordDelimiter(String recordDelimiter) {
+ this.recordDelimiter = recordDelimiter;
+ }
+
+ public String[] getFieldNames() {
+ return this.fieldNames;
+ }
+
+ public void setFieldNames(String[] fieldNames) {
+ this.fieldNames = fieldNames;
+ }
}
http://git-wip-us.apache.org/repos/asf/incubator-metron/blob/28c250d1/metron-platform/metron-parsers/src/main/scripts/start_parser_topology.sh
----------------------------------------------------------------------
diff --git a/metron-platform/metron-parsers/src/main/scripts/start_parser_topology.sh b/metron-platform/metron-parsers/src/main/scripts/start_parser_topology.sh
index 7000935..c5a5629 100755
--- a/metron-platform/metron-parsers/src/main/scripts/start_parser_topology.sh
+++ b/metron-platform/metron-parsers/src/main/scripts/start_parser_topology.sh
@@ -16,7 +16,7 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
-METRON_VERSION=0.1BETA
+METRON_VERSION=${project.version}
METRON_HOME=/usr/metron/$METRON_VERSION
TOPOLOGY_JAR=metron-parsers-$METRON_VERSION.jar
-storm jar $METRON_HOME/lib/$TOPOLOGY_JAR org.apache.storm.flux.Flux --remote $METRON_HOME/config/$1/remote.yaml --filter $METRON_HOME/config/parsers.properties
+storm jar $METRON_HOME/lib/$TOPOLOGY_JAR org.apache.storm.flux.Flux --remote $METRON_HOME/flux/$1/remote.yaml --filter $METRON_HOME/config/parsers.properties
http://git-wip-us.apache.org/repos/asf/incubator-metron/blob/28c250d1/metron-platform/metron-parsers/src/test/java/org/apache/metron/parsers/integration/PcapParserIntegrationTest.java
----------------------------------------------------------------------
diff --git a/metron-platform/metron-parsers/src/test/java/org/apache/metron/parsers/integration/PcapParserIntegrationTest.java b/metron-platform/metron-parsers/src/test/java/org/apache/metron/parsers/integration/PcapParserIntegrationTest.java
deleted file mode 100644
index 0dac76b..0000000
--- a/metron-platform/metron-parsers/src/test/java/org/apache/metron/parsers/integration/PcapParserIntegrationTest.java
+++ /dev/null
@@ -1,214 +0,0 @@
-/**
- * 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.parsers.integration;
-
-import com.google.common.collect.Iterables;
-import org.apache.hadoop.conf.Configuration;
-import org.apache.hadoop.fs.Path;
-import org.apache.hadoop.hbase.client.HTableInterface;
-import org.apache.hadoop.hbase.client.Result;
-import org.apache.hadoop.hbase.client.ResultScanner;
-import org.apache.hadoop.io.BytesWritable;
-import org.apache.hadoop.io.IntWritable;
-import org.apache.hadoop.io.SequenceFile;
-import org.apache.hadoop.io.SequenceFile.Reader;
-import org.apache.metron.TestConstants;
-import org.apache.metron.hbase.TableProvider;
-import org.apache.metron.integration.BaseIntegrationTest;
-import org.apache.metron.test.utils.UnitTestHelper;
-import org.apache.metron.integration.ComponentRunner;
-import org.apache.metron.integration.Processor;
-import org.apache.metron.integration.ReadinessState;
-import org.apache.metron.integration.components.FluxTopologyComponent;
-import org.apache.metron.integration.components.KafkaWithZKComponent;
-import org.apache.metron.test.mock.MockHTable;
-import org.apache.metron.parsers.pcap.PcapParser;
-import org.apache.metron.pcap.utils.PcapUtils;
-import org.json.simple.JSONObject;
-import org.junit.Assert;
-import org.junit.Test;
-
-import java.io.File;
-import java.io.IOException;
-import java.io.Serializable;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Properties;
-
-public class PcapParserIntegrationTest extends BaseIntegrationTest {
-
- private static String BASE_DIR = "pcap";
- private static String DATA_DIR = BASE_DIR + "/data_dir";
- private static String QUERY_DIR = BASE_DIR + "/query";
- private String topologiesDir = "./src/main/flux";
- private String targetDir = "target";
-
- public static class Provider implements TableProvider, Serializable {
- MockHTable.Provider provider = new MockHTable.Provider();
-
- @Override
- public HTableInterface getTable(Configuration config, String tableName) throws IOException {
- return provider.getTable(config, tableName);
- }
- }
-
- private File getOutDir(String targetDir) {
- File outDir = new File(new File(targetDir), DATA_DIR);
- if (!outDir.exists()) {
- outDir.mkdirs();
- }
-
- return outDir;
- }
-
- private File getQueryDir(String targetDir) {
- File outDir = new File(new File(targetDir), QUERY_DIR);
- if (!outDir.exists()) {
- outDir.mkdirs();
- }
- return outDir;
- }
-
- private static void clearOutDir(File outDir) {
- for (File f : outDir.listFiles()) {
- f.delete();
- }
- }
-
- private static Map<String, byte[]> readPcaps(Path pcapFile) throws IOException {
- SequenceFile.Reader reader = new SequenceFile.Reader(new Configuration(),
- Reader.file(pcapFile)
- );
- Map<String, byte[]> ret = new HashMap<>();
- IntWritable key = new IntWritable();
- BytesWritable value = new BytesWritable();
- PcapParser parser = new PcapParser();
- parser.init();
- while (reader.next(key, value)) {
- int keyInt = key.get();
- byte[] valueBytes = value.copyBytes();
- JSONObject message = parser.parse(valueBytes).get(0);
- if (parser.validate(message)) {
- ret.put(PcapUtils.getSessionKey(message), valueBytes);
- }
- }
- return ret;
- }
-
- @Test
- public void testTopology() throws Exception {
- if (!new File(topologiesDir).exists()) {
- topologiesDir = UnitTestHelper.findDir("topologies");
- }
- targetDir = UnitTestHelper.findDir("target");
- final String kafkaTopic = "pcap";
- final String tableName = "pcap";
- final String columnFamily = "t";
- final String columnIdentifier = "value";
- final File outDir = getOutDir(targetDir);
- final File queryDir = getQueryDir(targetDir);
- clearOutDir(outDir);
- clearOutDir(queryDir);
-
- File baseDir = new File(new File(targetDir), BASE_DIR);
- Assert.assertNotNull(topologiesDir);
- Assert.assertNotNull(targetDir);
- Path pcapFile = new Path(TestConstants.SAMPLE_DATA_INPUT_PATH + "PCAPExampleOutput");
- final Map<String, byte[]> pcapEntries = readPcaps(pcapFile);
- Assert.assertTrue(Iterables.size(pcapEntries.keySet()) > 0);
- final Properties topologyProperties = new Properties() {{
- setProperty("hbase.provider.impl", "" + Provider.class.getName());
- setProperty("spout.kafka.topic.pcap", kafkaTopic);
- setProperty("bolt.hbase.table.name", tableName);
- setProperty("bolt.hbase.table.fields", columnFamily + ":" + columnIdentifier);
- }};
- final KafkaWithZKComponent kafkaComponent = getKafkaComponent(topologyProperties, new ArrayList<KafkaWithZKComponent.Topic>() {{
- add(new KafkaWithZKComponent.Topic(kafkaTopic, 1));
- }});
-
- FluxTopologyComponent fluxComponent = new FluxTopologyComponent.Builder()
- .withTopologyLocation(new File(topologiesDir + "/pcap/test.yaml"))
- .withTopologyName("pcap")
- .withTopologyProperties(topologyProperties)
- .build();
-
- final MockHTable pcapTable = (MockHTable) MockHTable.Provider.addToCache(tableName, columnFamily);
-
- UnitTestHelper.verboseLogging();
- ComponentRunner runner = new ComponentRunner.Builder()
- .withComponent("kafka", kafkaComponent)
- .withComponent("storm", fluxComponent)
- .withMaxTimeMS(60000)
- .withMillisecondsBetweenAttempts(6000)
- .withNumRetries(10)
- .build();
- try {
- runner.start();
- fluxComponent.submitTopology();
- kafkaComponent.writeMessages(kafkaTopic, pcapEntries.values());
- System.out.println("Sent pcap data: " + pcapEntries.size());
- List<byte[]> messages = kafkaComponent.readMessages(kafkaTopic);
- Assert.assertEquals(pcapEntries.size(), messages.size());
- System.out.println("Wrote " + pcapEntries.size() + " to kafka");
- runner.process(new Processor<Void>() {
- @Override
- public ReadinessState process(ComponentRunner runner) {
- int hbaseCount = 0;
- try {
- System.out.println("Waiting...");
- ResultScanner resultScanner = pcapTable.getScanner(columnFamily.getBytes(), columnIdentifier.getBytes());
- while (resultScanner.next() != null) hbaseCount++;
- } catch (IOException e) {
- e.printStackTrace();
- }
- if (hbaseCount == pcapEntries.size()) {
- return ReadinessState.READY;
- } else {
- return ReadinessState.NOT_READY;
- }
- }
-
- @Override
- public Void getResult() {
- return null;
- }
- });
- ResultScanner resultScanner = pcapTable.getScanner(columnFamily.getBytes(), columnIdentifier.getBytes());
- Result result;
- int rowCount = 0;
- while ((result = resultScanner.next()) != null) {
- String rowKey = new String(result.getRow());
- byte[] hbaseValue = result.getValue(columnFamily.getBytes(), columnIdentifier.getBytes());
- byte[] originalValue = pcapEntries.get(rowKey);
- Assert.assertNotNull("Could not find pcap with key " + rowKey + " in sample data", originalValue);
- Assert.assertArrayEquals("Raw values are different for key " + rowKey, originalValue, hbaseValue);
- rowCount++;
- }
- Assert.assertEquals(pcapEntries.size(), rowCount);
- System.out.println("Ended");
- } catch (Exception e ) {
- e.printStackTrace();
- } finally {
- runner.stop();
- clearOutDir(outDir);
- clearOutDir(queryDir);
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-metron/blob/28c250d1/metron-platform/metron-pcap-backend/README.md
----------------------------------------------------------------------
diff --git a/metron-platform/metron-pcap-backend/README.md b/metron-platform/metron-pcap-backend/README.md
new file mode 100644
index 0000000..9969c02
--- /dev/null
+++ b/metron-platform/metron-pcap-backend/README.md
@@ -0,0 +1,75 @@
+# Metron PCAP Backend
+
+The purpose of the Metron PCAP backend is to create a storm topology
+capable of ingesting rapidly raw packet capture data directly into HDFS
+from Kafka.
+
+## The Sensors Feeding Kafka
+
+This component must be fed by fast packet capture components upstream
+via Kafka. The two supported components shipped with Metron are as follows:
+* The pycapa [tool](../../metron-sensors/pycapa) aimed at low-volume packet capture
+* The [DPDK](http://dpdk.org/) based [tool](../../metron-sensors/fastcapa) aimed at high-volume packet capture
+
+Both of these sensors feed kafka raw packet data directly into Kafka.
+The format of the record structure that this component expects is the
+following:
+* A key which is the byte representation of a 64-bit `unsigned long` representing a time-unit since the unix epoch
+* A value which is the raw packet data without header (either global pcap header or packet header)
+
+## The PCAP Topology
+
+The structure of the topology is extremely simple. In fact, it is a spout-only
+topology. The `Storm Kafka` spout is used but extended to allow a
+callback to be used rather than having a separate bolt.
+
+The following happens as part of this spout for each packet:
+* A custom `Scheme` is used which attaches the appropriate headers to the packet (both global and packet headers) using the timestamp in the key and the raw packet data in the value.
+* A callback is called which appends the packet data to a sequence file in HDFS.
+
+## The Files on HDFS
+
+The sequence files on HDFS fit the following pattern: `$BASE_PATH/pcap_$TOPIC_$TS_$PARTITION_$UUID`
+
+where
+* `BASE_PATH` is the base path to where pcap data is stored in HDFS
+* `TOPIC` is the kafka topic
+* `TS` is the timestamp, in nanoseconds since the unix epoch
+* `PARTITION` is the kafka partition
+* `UUID` the UUID for the storm worker
+
+These files contain a set of packet data with headers on them in
+sequence files.
+
+## Configuration
+
+The configuration file for the Flux topology is located at
+`$METRON_HOME/config/etc/env/pcap.properties` and the possible options
+are as follows:
+* `spout.kafka.topic.pcap` : The kafka topic to listen to
+* `kafka.zk` : The comma separated zookeeper quorum (i.e. host:2181,host2:2181)
+* `kafka.pcap.start` : One of `START`, `END`, `WHERE_I_LEFT_OFF` representing where to start listening on the queue.
+* `kafka.pcap.numPackets` : The number of packets to keep in one file.
+* `kafka.pcap.maxTimeMS` : The number of packets to keep in one file in terms of duration (in milliseconds). For instance, you may only want to keep an hour's worth of packets in a given file.
+* `kafka.pcap.ts_scheme` : One of `FROM_KEY` or `FROM_VALUE`. You really only want `FROM_KEY` as that fits the current tooling. `FROM_VALUE` assumes that fully headerized packets are coming in on the value, which is legacy.
+* `kafka.pcap.out` : The directory in HDFS to store the packet capture data
+* `kafka.pcap.ts_granularity` : The granularity of timing used in the timestamps. One of `MILLISECONDS`, `MICROSECONDS`, or `NANOSECONDS` representing milliseconds, microseconds or nanoseconds since the unix epoch (respectively).
+
+## Starting the Topology
+
+To assist in starting the topology, a utility script which takes no
+arguments has been created to make this very simple. Simply, execute
+`$METRON_HOME/bin/start_pcap_topology.sh`.
+
+## Utilities
+
+In order to ensure that data can be read back out, a utility,
+`$METRON_HOME/bin/pcap_inspector.sh` has been
+created to read portions of the sequence files.
+
+```
+usage: PcapInspector
+ -h,--help Generate Help screen
+ -i,--input <SEQ_FILE> Input sequence file on HDFS
+ -n,--num_packets <N> Number of packets to dump
+```
http://git-wip-us.apache.org/repos/asf/incubator-metron/blob/28c250d1/metron-platform/metron-pcap-backend/pom.xml
----------------------------------------------------------------------
diff --git a/metron-platform/metron-pcap-backend/pom.xml b/metron-platform/metron-pcap-backend/pom.xml
new file mode 100644
index 0000000..402ee40
--- /dev/null
+++ b/metron-platform/metron-pcap-backend/pom.xml
@@ -0,0 +1,234 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+ 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.
+ -->
+
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+ <modelVersion>4.0.0</modelVersion>
+ <parent>
+ <groupId>org.apache.metron</groupId>
+ <artifactId>metron-platform</artifactId>
+ <version>0.1BETA</version>
+ </parent>
+ <artifactId>metron-pcap-backend</artifactId>
+ <name>Metron PCAP Backend</name>
+ <description>The Metron PCAP Backend Topology</description>
+ <properties>
+ <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
+ <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
+ <commons.config.version>1.10</commons.config.version>
+ </properties>
+ <dependencies>
+ <dependency>
+ <groupId>org.apache.metron</groupId>
+ <artifactId>metron-common</artifactId>
+ <version>${project.parent.version}</version>
+ </dependency>
+ <dependency>
+ <groupId>com.google.guava</groupId>
+ <artifactId>guava</artifactId>
+ <version>${global_hbase_guava_version}</version>
+ <scope>compile</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.storm</groupId>
+ <artifactId>flux-core</artifactId>
+ <version>${global_flux_version}</version>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.storm</groupId>
+ <artifactId>storm-kafka</artifactId>
+ <version>${global_storm_version}</version>
+ <exclusions>
+ <exclusion>
+ <artifactId>org.apache.curator</artifactId>
+ <groupId>curator-client</groupId>
+ </exclusion>
+ </exclusions>
+ </dependency>
+ <dependency>
+ <groupId>junit</groupId>
+ <artifactId>junit</artifactId>
+ <version>${global_junit_version}</version>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.mockito</groupId>
+ <artifactId>mockito-all</artifactId>
+ <version>${global_mockito_version}</version>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>nl.jqno.equalsverifier</groupId>
+ <artifactId>equalsverifier</artifactId>
+ <version>2.0.2</version>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.hadoop</groupId>
+ <artifactId>hadoop-common</artifactId>
+ <version>${global_hadoop_version}</version>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.hadoop</groupId>
+ <artifactId>hadoop-hdfs</artifactId>
+ <version>${global_hadoop_version}</version>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.hbase</groupId>
+ <artifactId>hbase-common</artifactId>
+ <version>${global_hbase_version}</version>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.kafka</groupId>
+ <artifactId>kafka_2.9.2</artifactId>
+ <version>${global_kafka_version}</version>
+ <exclusions>
+ <exclusion>
+ <groupId>log4j</groupId>
+ <artifactId>log4j</artifactId>
+ </exclusion>
+ </exclusions>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.storm</groupId>
+ <artifactId>storm-core</artifactId>
+ <version>${global_storm_version}</version>
+ <scope>provided</scope>
+ <exclusions>
+ <exclusion>
+ <artifactId>servlet-api</artifactId>
+ <groupId>javax.servlet</groupId>
+ </exclusion>
+ <exclusion>
+ <artifactId>log4j-over-slf4j</artifactId>
+ <groupId>org.slf4j</groupId>
+ </exclusion>
+ </exclusions>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.metron</groupId>
+ <artifactId>metron-pcap</artifactId>
+ <version>${project.parent.version}</version>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.metron</groupId>
+ <artifactId>metron-integration-test</artifactId>
+ <version>${project.parent.version}</version>
+ <scope>test</scope>
+ </dependency>
+ </dependencies>
+
+ <reporting>
+ <plugins>
+ <!-- Normally, dependency report takes time, skip it -->
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-project-info-reports-plugin</artifactId>
+ <version>2.7</version>
+
+ <configuration>
+ <dependencyLocationsEnabled>false</dependencyLocationsEnabled>
+ </configuration>
+ </plugin>
+ <plugin>
+ <groupId>org.codehaus.mojo</groupId>
+ <artifactId>emma-maven-plugin</artifactId>
+ <version>1.0-alpha-3</version>
+ </plugin>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-pmd-plugin</artifactId>
+ <configuration>
+ <targetJdk>${global_java_version}</targetJdk>
+ </configuration>
+ </plugin>
+ </plugins>
+ </reporting>
+ <build>
+ <plugins>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-compiler-plugin</artifactId>
+ <version>3.1</version>
+ <configuration>
+ <source>${global_java_version}</source>
+ <compilerArgument>-Xlint:unchecked</compilerArgument>
+ <target>${global_java_version}</target>
+ </configuration>
+ </plugin>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-shade-plugin</artifactId>
+ <version>${global_shade_version}</version>
+ <configuration>
+ <createDependencyReducedPom>true</createDependencyReducedPom>
+ <artifactSet>
+ <excludes>
+ <exclude>*slf4j*</exclude>
+ </excludes>
+ </artifactSet>
+ </configuration>
+ <executions>
+ <execution>
+ <phase>package</phase>
+ <goals>
+ <goal>shade</goal>
+ </goals>
+ <configuration>
+ <relocations>
+ <relocation>
+ <pattern>com.google.common</pattern>
+ <shadedPattern>org.apache.metron.guava</shadedPattern>
+ </relocation>
+ </relocations>
+ <transformers>
+ <transformer
+ implementation="org.apache.maven.plugins.shade.resource.DontIncludeResourceTransformer">
+ <resource>.yaml</resource>
+ </transformer>
+ <transformer
+ implementation="org.apache.maven.plugins.shade.resource.ServicesResourceTransformer" />
+ <transformer
+ implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
+ <mainClass></mainClass>
+ </transformer>
+ </transformers>
+ </configuration>
+ </execution>
+ </executions>
+ </plugin>
+ <plugin>
+ <artifactId>maven-assembly-plugin</artifactId>
+ <configuration>
+ <descriptor>src/main/assembly/assembly.xml</descriptor>
+ </configuration>
+ <executions>
+ <execution>
+ <id>make-assembly</id> <!-- this is used for inheritance merges -->
+ <phase>package</phase> <!-- bind to the packaging phase -->
+ <goals>
+ <goal>single</goal>
+ </goals>
+ </execution>
+ </executions>
+ </plugin>
+
+ </plugins>
+ <resources>
+ <resource>
+ <directory>src/main/resources</directory>
+ </resource>
+ </resources>
+ </build>
+</project>
http://git-wip-us.apache.org/repos/asf/incubator-metron/blob/28c250d1/metron-platform/metron-pcap-backend/src/main/assembly/assembly.xml
----------------------------------------------------------------------
diff --git a/metron-platform/metron-pcap-backend/src/main/assembly/assembly.xml b/metron-platform/metron-pcap-backend/src/main/assembly/assembly.xml
new file mode 100644
index 0000000..b211113
--- /dev/null
+++ b/metron-platform/metron-pcap-backend/src/main/assembly/assembly.xml
@@ -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.
+ -->
+
+<assembly>
+ <id>archive</id>
+ <formats>
+ <format>tar.gz</format>
+ </formats>
+ <includeBaseDirectory>false</includeBaseDirectory>
+ <fileSets>
+ <fileSet>
+ <directory>${project.basedir}/src/main/config</directory>
+ <outputDirectory>/config</outputDirectory>
+ <useDefaultExcludes>true</useDefaultExcludes>
+ <excludes>
+ <exclude>**/*.formatted</exclude>
+ <exclude>**/*.filtered</exclude>
+ </excludes>
+ <fileMode>0644</fileMode>
+ <lineEnding>unix</lineEnding>
+ </fileSet>
+ <fileSet>
+ <directory>${project.basedir}/src/main/scripts</directory>
+ <outputDirectory>/bin</outputDirectory>
+ <useDefaultExcludes>true</useDefaultExcludes>
+ <excludes>
+ <exclude>**/*.formatted</exclude>
+ <exclude>**/*.filtered</exclude>
+ </excludes>
+ <fileMode>0755</fileMode>
+ <lineEnding>unix</lineEnding>
+ <filtered>true</filtered>
+ </fileSet>
+ <fileSet>
+ <directory>${project.basedir}/src/main/flux</directory>
+ <outputDirectory>/flux</outputDirectory>
+ <useDefaultExcludes>true</useDefaultExcludes>
+ <excludes>
+ <exclude>**/*.formatted</exclude>
+ <exclude>**/*.filtered</exclude>
+ </excludes>
+ <fileMode>0644</fileMode>
+ <lineEnding>unix</lineEnding>
+ </fileSet>
+ <fileSet>
+ <directory>${project.basedir}/target</directory>
+ <includes>
+ <include>${project.artifactId}-${project.version}.jar</include>
+ </includes>
+ <outputDirectory>/lib</outputDirectory>
+ <useDefaultExcludes>true</useDefaultExcludes>
+ </fileSet>
+ </fileSets>
+</assembly>
http://git-wip-us.apache.org/repos/asf/incubator-metron/blob/28c250d1/metron-platform/metron-pcap-backend/src/main/config/pcap.properties
----------------------------------------------------------------------
diff --git a/metron-platform/metron-pcap-backend/src/main/config/pcap.properties b/metron-platform/metron-pcap-backend/src/main/config/pcap.properties
new file mode 100644
index 0000000..48810c5
--- /dev/null
+++ b/metron-platform/metron-pcap-backend/src/main/config/pcap.properties
@@ -0,0 +1,24 @@
+# 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.
+
+spout.kafka.topic.pcap=pcap
+kafka.zk=node1:2181
+kafka.pcap.start=END
+kafka.pcap.numPackets=1000
+kafka.pcap.maxTimeMS=300000
+kafka.pcap.ts_scheme=FROM_KEY
+kafka.pcap.out=/apps/metron/pcap
+kafka.pcap.ts_granularity=MICROSECONDS
http://git-wip-us.apache.org/repos/asf/incubator-metron/blob/28c250d1/metron-platform/metron-pcap-backend/src/main/flux/pcap/remote.yaml
----------------------------------------------------------------------
diff --git a/metron-platform/metron-pcap-backend/src/main/flux/pcap/remote.yaml b/metron-platform/metron-pcap-backend/src/main/flux/pcap/remote.yaml
new file mode 100644
index 0000000..32f994f
--- /dev/null
+++ b/metron-platform/metron-pcap-backend/src/main/flux/pcap/remote.yaml
@@ -0,0 +1,66 @@
+# 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.
+
+name: "pcap"
+config:
+ topology.workers: 1
+
+components:
+ - id: "zkHosts"
+ className: "storm.kafka.ZkHosts"
+ constructorArgs:
+ - "${kafka.zk}"
+ - id: "kafkaConfig"
+ className: "org.apache.metron.spout.pcap.SpoutConfig"
+ constructorArgs:
+ # zookeeper hosts
+ - ref: "zkHosts"
+ # topic name
+ - "${spout.kafka.topic.pcap}"
+ # zk root
+ - ""
+ # id
+ - "${spout.kafka.topic.pcap}"
+ configMethods:
+ - name: "from"
+ args:
+ - "${kafka.pcap.start}"
+ - name: "withTimestampScheme"
+ args:
+ - "${kafka.pcap.ts_scheme}"
+ - "${kafka.pcap.ts_granularity}"
+
+ - id: "writerConfig"
+ className: "org.apache.metron.spout.pcap.HDFSWriterConfig"
+ configMethods:
+ - name: "withOutputPath"
+ args:
+ - "${kafka.pcap.out}"
+ - name: "withNumPackets"
+ args:
+ - ${kafka.pcap.numPackets}
+ - name: "withMaxTimeMS"
+ args:
+ - ${kafka.pcap.maxTimeMS}
+ - name: "withZookeeperQuorum"
+ args:
+ - "${kafka.zk}"
+spouts:
+ - id: "kafkaSpout"
+ className: "org.apache.metron.spout.pcap.KafkaToHDFSSpout"
+ constructorArgs:
+ - ref: "kafkaConfig"
+ - ref: "writerConfig"
http://git-wip-us.apache.org/repos/asf/incubator-metron/blob/28c250d1/metron-platform/metron-pcap-backend/src/main/java/org/apache/metron/spout/pcap/HDFSWriterCallback.java
----------------------------------------------------------------------
diff --git a/metron-platform/metron-pcap-backend/src/main/java/org/apache/metron/spout/pcap/HDFSWriterCallback.java b/metron-platform/metron-pcap-backend/src/main/java/org/apache/metron/spout/pcap/HDFSWriterCallback.java
new file mode 100644
index 0000000..b2f261e
--- /dev/null
+++ b/metron-platform/metron-pcap-backend/src/main/java/org/apache/metron/spout/pcap/HDFSWriterCallback.java
@@ -0,0 +1,181 @@
+/**
+ * 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.spout.pcap;
+
+import com.google.common.base.Function;
+import com.google.common.base.Joiner;
+import com.google.common.collect.ImmutableList;
+import org.apache.commons.collections.map.HashedMap;
+import org.apache.hadoop.conf.Configuration;
+import org.apache.hadoop.fs.FSDataOutputStream;
+import org.apache.hadoop.fs.FileSystem;
+import org.apache.hadoop.fs.Path;
+import org.apache.hadoop.io.BytesWritable;
+import org.apache.hadoop.io.LongWritable;
+import org.apache.hadoop.io.SequenceFile;
+import org.apache.log4j.Logger;
+import storm.kafka.Callback;
+import storm.kafka.EmitContext;
+import storm.kafka.PartitionManager;
+
+import javax.annotation.Nullable;
+import java.io.Closeable;
+import java.io.IOException;
+import java.util.EnumSet;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+public class HDFSWriterCallback implements Callback {
+ static final long serialVersionUID = 0xDEADBEEFL;
+ private static final Logger LOG = Logger.getLogger(HDFSWriterCallback.class);
+
+ static class Partition {
+ String topic;
+ int partition;
+
+ public Partition(String topic, int partition) {
+ this.topic = topic;
+ this.partition = partition;
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (this == o) return true;
+ if (o == null || getClass() != o.getClass()) return false;
+
+ Partition partition1 = (Partition) o;
+
+ if (partition != partition1.partition) return false;
+ return topic != null ? topic.equals(partition1.topic) : partition1.topic == null;
+
+ }
+
+ @Override
+ public int hashCode() {
+ int result = topic != null ? topic.hashCode() : 0;
+ result = 31 * result + partition;
+ return result;
+ }
+
+ @Override
+ public String toString() {
+ return "Partition{" +
+ "topic='" + topic + '\'' +
+ ", partition=" + partition +
+ '}';
+ }
+ }
+
+ private HDFSWriterConfig config;
+ private EmitContext context;
+ private Map<Partition, PartitionHDFSWriter> writers = new HashMap<>();
+ private PartitionHDFSWriter lastWriter = null;
+ private String topic;
+ public HDFSWriterCallback() {
+ }
+
+ public HDFSWriterCallback withConfig(HDFSWriterConfig config) {
+ LOG.info("Configured: " + config);
+ this.config = config;
+ return this;
+ }
+ @Override
+ public List<Object> apply(List<Object> tuple, EmitContext context) {
+
+ List<Object> keyValue = (List<Object>) tuple.get(0);
+ LongWritable ts = (LongWritable) keyValue.get(0);
+ BytesWritable rawPacket = (BytesWritable)keyValue.get(1);
+ try {
+ getWriter(new Partition( topic
+ , context.get(EmitContext.Type.PARTITION))
+ ).handle(ts, rawPacket);
+ } catch (IOException e) {
+ LOG.error(e.getMessage(), e);
+ //drop? not sure..
+ }
+ return tuple;
+ }
+
+ private PartitionHDFSWriter getWriter(Partition partition) {
+ //if we have just one partition or a run from a single partition in this spout, we don't want a map lookup
+ if(lastWriter != null && lastWriter.getTopic().equals(partition.topic) && lastWriter.getPartition() == partition.partition) {
+ return lastWriter;
+ }
+ lastWriter = writers.get(partition);
+ if(lastWriter == null) {
+ lastWriter = new PartitionHDFSWriter( partition.topic
+ , partition.partition
+ , context.get(EmitContext.Type.UUID)
+ , config
+ );
+ writers.put(partition, lastWriter);
+ }
+ return lastWriter;
+ }
+
+ @Override
+ public void initialize(EmitContext context) {
+ this.context = context;
+ this.topic = context.get(EmitContext.Type.TOPIC);
+ }
+
+ /**
+ * Closes this resource, relinquishing any underlying resources.
+ * This method is invoked automatically on objects managed by the
+ * {@code try}-with-resources statement.
+ * <p/>
+ * <p>While this interface method is declared to throw {@code
+ * Exception}, implementers are <em>strongly</em> encouraged to
+ * declare concrete implementations of the {@code close} method to
+ * throw more specific exceptions, or to throw no exception at all
+ * if the close operation cannot fail.
+ * <p/>
+ * <p><em>Implementers of this interface are also strongly advised
+ * to not have the {@code close} method throw {@link
+ * InterruptedException}.</em>
+ * <p/>
+ * This exception interacts with a thread's interrupted status,
+ * and runtime misbehavior is likely to occur if an {@code
+ * InterruptedException} is {@linkplain Throwable#addSuppressed
+ * suppressed}.
+ * <p/>
+ * More generally, if it would cause problems for an
+ * exception to be suppressed, the {@code AutoCloseable.close}
+ * method should not throw it.
+ * <p/>
+ * <p>Note that unlike the {@link Closeable#close close}
+ * method of {@link Closeable}, this {@code close} method
+ * is <em>not</em> required to be idempotent. In other words,
+ * calling this {@code close} method more than once may have some
+ * visible side effect, unlike {@code Closeable.close} which is
+ * required to have no effect if called more than once.
+ * <p/>
+ * However, implementers of this interface are strongly encouraged
+ * to make their {@code close} methods idempotent.
+ *
+ * @throws Exception if this resource cannot be closed
+ */
+ @Override
+ public void close() throws Exception {
+ for(PartitionHDFSWriter writer : writers.values()) {
+ writer.close();
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-metron/blob/28c250d1/metron-platform/metron-pcap-backend/src/main/java/org/apache/metron/spout/pcap/HDFSWriterConfig.java
----------------------------------------------------------------------
diff --git a/metron-platform/metron-pcap-backend/src/main/java/org/apache/metron/spout/pcap/HDFSWriterConfig.java b/metron-platform/metron-pcap-backend/src/main/java/org/apache/metron/spout/pcap/HDFSWriterConfig.java
new file mode 100644
index 0000000..b6efbc5
--- /dev/null
+++ b/metron-platform/metron-pcap-backend/src/main/java/org/apache/metron/spout/pcap/HDFSWriterConfig.java
@@ -0,0 +1,98 @@
+/**
+ * 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.spout.pcap;
+
+import com.google.common.base.Splitter;
+import com.google.common.collect.Iterables;
+import org.apache.metron.common.utils.timestamp.TimestampConverters;
+
+import java.io.Serializable;
+import java.util.ArrayList;
+import java.util.List;
+
+public class HDFSWriterConfig implements Serializable {
+ static final long serialVersionUID = 0xDEADBEEFL;
+ private long numPackets;
+ private long maxTimeNS;
+ private String outputPath;
+ private String zookeeperQuorum;
+
+ public HDFSWriterConfig withOutputPath(String path) {
+ outputPath = path;
+ return this;
+ }
+
+ public HDFSWriterConfig withNumPackets(long n) {
+ numPackets = n;
+ return this;
+ }
+
+ public HDFSWriterConfig withMaxTimeMS(long t) {
+ maxTimeNS = TimestampConverters.MILLISECONDS.toNanoseconds(t);
+ return this;
+ }
+
+ public HDFSWriterConfig withZookeeperQuorum(String zookeeperQuorum) {
+ this.zookeeperQuorum = zookeeperQuorum;
+ return this;
+ }
+
+ public List<String> getZookeeperServers() {
+ List<String> out = new ArrayList<>();
+ if(zookeeperQuorum != null) {
+ for (String hostPort : Splitter.on(',').split(zookeeperQuorum)) {
+ Iterable<String> tokens = Splitter.on(':').split(hostPort);
+ String host = Iterables.getFirst(tokens, null);
+ if(host != null) {
+ out.add(host);
+ }
+ }
+ }
+ return out;
+ }
+
+ public Integer getZookeeperPort() {
+ if(zookeeperQuorum != null) {
+ String hostPort = Iterables.getFirst(Splitter.on(',').split(zookeeperQuorum), null);
+ String portStr = Iterables.getLast(Splitter.on(':').split(hostPort));
+ return Integer.parseInt(portStr);
+ }
+ return null;
+ }
+
+ public String getOutputPath() {
+ return outputPath;
+ }
+
+ public long getNumPackets() {
+ return numPackets;
+ }
+
+ public long getMaxTimeNS() {
+ return maxTimeNS;
+ }
+
+ @Override
+ public String toString() {
+ return "HDFSWriterConfig{" +
+ "numPackets=" + numPackets +
+ ", maxTimeNS=" + maxTimeNS +
+ ", outputPath='" + outputPath + '\'' +
+ '}';
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-metron/blob/28c250d1/metron-platform/metron-pcap-backend/src/main/java/org/apache/metron/spout/pcap/KafkaToHDFSSpout.java
----------------------------------------------------------------------
diff --git a/metron-platform/metron-pcap-backend/src/main/java/org/apache/metron/spout/pcap/KafkaToHDFSSpout.java b/metron-platform/metron-pcap-backend/src/main/java/org/apache/metron/spout/pcap/KafkaToHDFSSpout.java
new file mode 100644
index 0000000..d87e2c0
--- /dev/null
+++ b/metron-platform/metron-pcap-backend/src/main/java/org/apache/metron/spout/pcap/KafkaToHDFSSpout.java
@@ -0,0 +1,38 @@
+/**
+ * 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.spout.pcap;
+
+import storm.kafka.Callback;
+import storm.kafka.CallbackKafkaSpout;
+
+public class KafkaToHDFSSpout extends CallbackKafkaSpout {
+ static final long serialVersionUID = 0xDEADBEEFL;
+ HDFSWriterConfig config = null;
+ public KafkaToHDFSSpout(SpoutConfig spoutConfig, HDFSWriterConfig config) {
+ super(spoutConfig, HDFSWriterCallback.class);
+ this.config = config;
+ }
+
+ @Override
+ protected Callback createCallback(Class<? extends Callback> callbackClass) {
+ return new HDFSWriterCallback().withConfig(config);
+ }
+
+
+}