You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@spot.apache.org by na...@apache.org on 2017/09/26 22:41:10 UTC
[07/50] [abbrv] incubator-spot git commit: SPOT-166 Schema validation.
SPOT-166 Schema validation.
Added schema validation based on columns required for model training.
Updated each pipeline (DNS, Flow, Proxy) so the schema is validated before performing any other activity.
Added unit test for schema validation.
Updated main activity to show error about bad schema if any.
Application now will print what fields are not matching the expected schema.
Project: http://git-wip-us.apache.org/repos/asf/incubator-spot/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-spot/commit/9c537a7a
Tree: http://git-wip-us.apache.org/repos/asf/incubator-spot/tree/9c537a7a
Diff: http://git-wip-us.apache.org/repos/asf/incubator-spot/diff/9c537a7a
Branch: refs/heads/SPOT-181_ODM
Commit: 9c537a7a82a582fb7744f05dd44034015077f46c
Parents: ab11e8c
Author: Ricardo Barona <ri...@intel.com>
Authored: Thu Jun 29 16:43:12 2017 -0500
Committer: Ricardo Barona <ri...@intel.com>
Committed: Thu Jul 27 12:51:02 2017 -0500
----------------------------------------------------------------------
.../org/apache/spot/SuspiciousConnects.scala | 18 ++--
.../dns/DNSSuspiciousConnectsAnalysis.scala | 61 +++++++++-----
.../FlowSuspiciousConnectsAnalysis.scala | 50 +++++++----
.../model/FlowSuspiciousConnectsModel.scala | 2 +-
.../proxy/ProxySuspiciousConnectsAnalysis.scala | 59 ++++++++-----
.../proxy/ProxySuspiciousConnectsModel.scala | 18 +++-
.../utilities/data/validation/InputSchema.scala | 48 +++++++++++
.../dns/DNSSuspiciousConnectsAnalysisTest.scala | 56 ++++++++++++-
.../org/apache/spot/netflow/FlowRecord.scala | 18 ++++
.../FlowSuspiciousConnectsAnalysisTest.scala | 56 ++++++++++++-
.../ProxySuspiciousConnectsAnalysisTest.scala | 87 +++++++++++++++++++-
.../data/validation/InputSchemaTest.scala | 53 ++++++++++++
12 files changed, 452 insertions(+), 74 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/incubator-spot/blob/9c537a7a/spot-ml/src/main/scala/org/apache/spot/SuspiciousConnects.scala
----------------------------------------------------------------------
diff --git a/spot-ml/src/main/scala/org/apache/spot/SuspiciousConnects.scala b/spot-ml/src/main/scala/org/apache/spot/SuspiciousConnects.scala
index f3f122e..50917df 100644
--- a/spot-ml/src/main/scala/org/apache/spot/SuspiciousConnects.scala
+++ b/spot-ml/src/main/scala/org/apache/spot/SuspiciousConnects.scala
@@ -71,12 +71,12 @@ object SuspiciousConnects {
}
val results: Option[SuspiciousConnectsAnalysisResults] = analysis match {
- case "flow" => Some(FlowSuspiciousConnectsAnalysis.run(config, sparkSession, logger,
- inputDataFrame))
- case "dns" => Some(DNSSuspiciousConnectsAnalysis.run(config, sparkSession, logger,
- inputDataFrame))
- case "proxy" => Some(ProxySuspiciousConnectsAnalysis.run(config, sparkSession, logger,
- inputDataFrame))
+ case "flow" => FlowSuspiciousConnectsAnalysis.run(config, sparkSession, logger,
+ inputDataFrame)
+ case "dns" => DNSSuspiciousConnectsAnalysis.run(config, sparkSession, logger,
+ inputDataFrame)
+ case "proxy" => ProxySuspiciousConnectsAnalysis.run(config, sparkSession, logger,
+ inputDataFrame)
case _ => None
}
@@ -103,7 +103,11 @@ object SuspiciousConnects {
InvalidDataHandler.showAndSaveInvalidRecords(invalidRecords, config.hdfsScoredConnect, logger)
}
- case None => logger.error("Unsupported (or misspelled) analysis: " + analysis)
+ case None => logger.error(s"Something went wrong while trying to run Suspicious Connects Analysis")
+ logger.error(s"The value of parameter analysis (provided: $analysis) is any of the valid analysis types? " +
+ s"(flow, dns, proxy).")
+ logger.error("If analysis type is correct please check for other errors like schema not matching or " +
+ "bad spark parameters")
}
sparkSession.stop()
http://git-wip-us.apache.org/repos/asf/incubator-spot/blob/9c537a7a/spot-ml/src/main/scala/org/apache/spot/dns/DNSSuspiciousConnectsAnalysis.scala
----------------------------------------------------------------------
diff --git a/spot-ml/src/main/scala/org/apache/spot/dns/DNSSuspiciousConnectsAnalysis.scala b/spot-ml/src/main/scala/org/apache/spot/dns/DNSSuspiciousConnectsAnalysis.scala
index a1ec1ac..e0c8068 100644
--- a/spot-ml/src/main/scala/org/apache/spot/dns/DNSSuspiciousConnectsAnalysis.scala
+++ b/spot-ml/src/main/scala/org/apache/spot/dns/DNSSuspiciousConnectsAnalysis.scala
@@ -26,7 +26,7 @@ import org.apache.spot.SuspiciousConnectsArgumentParser.SuspiciousConnectsConfig
import org.apache.spot.dns.DNSSchema._
import org.apache.spot.dns.model.DNSSuspiciousConnectsModel
import org.apache.spot.proxy.ProxySchema.Score
-import org.apache.spot.utilities.data.validation.{InvalidDataHandler => dataValidation}
+import org.apache.spot.utilities.data.validation.{InputSchema, InvalidDataHandler => dataValidation}
/**
* The suspicious connections analysis of DNS log data develops a probabilistic model the DNS queries
@@ -62,38 +62,45 @@ object DNSSuspiciousConnectsAnalysis {
* @param logger
*/
def run(config: SuspiciousConnectsConfig, sparkSession: SparkSession, logger: Logger,
- inputDNSRecords: DataFrame): SuspiciousConnectsAnalysisResults = {
+ inputDNSRecords: DataFrame): Option[SuspiciousConnectsAnalysisResults] = {
logger.info("Starting DNS suspicious connects analysis.")
- val dnsRecords = filterRecords(inputDNSRecords)
- .select(InSchema: _*)
- .na.fill(DefaultQueryClass, Seq(QueryClass))
- .na.fill(DefaultQueryType, Seq(QueryType))
- .na.fill(DefaultQueryResponseCode, Seq(QueryResponseCode))
+ logger.info("Validating schema...")
+ val schemaValidationResults = validateSchema(inputDNSRecords)
- logger.info("Fitting probabilistic model to data")
- val model =
- DNSSuspiciousConnectsModel.trainModel(sparkSession, logger, config, dnsRecords)
+ if (schemaValidationResults.length > InputSchema.ResponseDefaultSize) {
+ schemaValidationResults.foreach(logger.error(_))
+ None
+ } else {
+ val dnsRecords = filterRecords(inputDNSRecords)
+ .select(InSchema: _*)
+ .na.fill(DefaultQueryClass, Seq(QueryClass))
+ .na.fill(DefaultQueryType, Seq(QueryType))
+ .na.fill(DefaultQueryResponseCode, Seq(QueryResponseCode))
- logger.info("Identifying outliers")
- val scoredDNSRecords = model.score(sparkSession, dnsRecords, config.userDomain, config.precisionUtility)
+ logger.info("Fitting probabilistic model to data")
+ val model =
+ DNSSuspiciousConnectsModel.trainModel(sparkSession, logger, config, dnsRecords)
- val filteredScored = filterScoredRecords(scoredDNSRecords, config.threshold)
+ logger.info("Identifying outliers")
+ val scoredDNSRecords = model.score(sparkSession, dnsRecords, config.userDomain, config.precisionUtility)
- val orderedDNSRecords = filteredScored.orderBy(Score)
+ val filteredScored = filterScoredRecords(scoredDNSRecords, config.threshold)
- val mostSuspiciousDNSRecords =
- if (config.maxResults > 0) orderedDNSRecords.limit(config.maxResults)
- else orderedDNSRecords
+ val orderedDNSRecords = filteredScored.orderBy(Score)
- val outputDNSRecords = mostSuspiciousDNSRecords.select(OutSchema: _*)
+ val mostSuspiciousDNSRecords =
+ if (config.maxResults > 0) orderedDNSRecords.limit(config.maxResults)
+ else orderedDNSRecords
- val invalidDNSRecords = filterInvalidRecords(inputDNSRecords).select(InSchema: _*)
+ val outputDNSRecords = mostSuspiciousDNSRecords.select(OutSchema: _*)
- SuspiciousConnectsAnalysisResults(outputDNSRecords, invalidDNSRecords)
+ val invalidDNSRecords = filterInvalidRecords(inputDNSRecords).select(InSchema: _*)
+ Option(SuspiciousConnectsAnalysisResults(outputDNSRecords, invalidDNSRecords))
+ }
}
@@ -158,7 +165,7 @@ object DNSSuspiciousConnectsAnalysis {
/**
*
* @param scoredDNSRecords scored DNS records.
- * @param threshold score tolerance.
+ * @param threshold score tolerance.
* @return
*/
def filterScoredRecords(scoredDNSRecords: DataFrame, threshold: Double): DataFrame = {
@@ -170,4 +177,16 @@ object DNSSuspiciousConnectsAnalysis {
scoredDNSRecords.filter(filteredDNSRecordsFilter)
}
+ /**
+ * Validates incoming data matches required schema for model training and scoring.
+ *
+ * @param inputDNSRecords incoming data frame
+ * @return
+ */
+ def validateSchema(inputDNSRecords: DataFrame): Seq[String] = {
+
+ InputSchema.validate(inputDNSRecords.schema, DNSSuspiciousConnectsModel.ModelSchema)
+
+ }
+
}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-spot/blob/9c537a7a/spot-ml/src/main/scala/org/apache/spot/netflow/FlowSuspiciousConnectsAnalysis.scala
----------------------------------------------------------------------
diff --git a/spot-ml/src/main/scala/org/apache/spot/netflow/FlowSuspiciousConnectsAnalysis.scala b/spot-ml/src/main/scala/org/apache/spot/netflow/FlowSuspiciousConnectsAnalysis.scala
index b6fe791..a355cfb 100644
--- a/spot-ml/src/main/scala/org/apache/spot/netflow/FlowSuspiciousConnectsAnalysis.scala
+++ b/spot-ml/src/main/scala/org/apache/spot/netflow/FlowSuspiciousConnectsAnalysis.scala
@@ -25,7 +25,7 @@ import org.apache.spot.SuspiciousConnects.SuspiciousConnectsAnalysisResults
import org.apache.spot.SuspiciousConnectsArgumentParser.SuspiciousConnectsConfig
import org.apache.spot.netflow.FlowSchema._
import org.apache.spot.netflow.model.FlowSuspiciousConnectsModel
-import org.apache.spot.utilities.data.validation.{InvalidDataHandler => dataValidation}
+import org.apache.spot.utilities.data.validation.{InputSchema, InvalidDataHandler => dataValidation}
/**
@@ -83,32 +83,40 @@ object FlowSuspiciousConnectsAnalysis {
* @return
*/
def run(config: SuspiciousConnectsConfig, sparkSession: SparkSession, logger: Logger,
- inputFlowRecords: DataFrame): SuspiciousConnectsAnalysisResults = {
+ inputFlowRecords: DataFrame): Option[SuspiciousConnectsAnalysisResults] = {
logger.info("Starting flow suspicious connects analysis.")
- val flowRecords = filterRecords(inputFlowRecords).select(InSchema: _*)
+ logger.info("Validating schema...")
+ val schemaValidationResults = validateSchema(inputFlowRecords)
- logger.info("Fitting probabilistic model to data")
- val model =
- FlowSuspiciousConnectsModel.trainModel(sparkSession, logger, config, flowRecords)
+ if (schemaValidationResults.length > InputSchema.ResponseDefaultSize) {
+ schemaValidationResults.foreach(logger.error(_))
+ None
- logger.info("Identifying outliers")
- val scoredFlowRecords = model.score(sparkSession, flowRecords, config.precisionUtility)
+ } else {
+ val flowRecords = filterRecords(inputFlowRecords).select(InSchema: _*)
- val filteredScored = filterScoredRecords(scoredFlowRecords, config.threshold)
+ logger.info("Fitting probabilistic model to data")
+ val model =
+ FlowSuspiciousConnectsModel.trainModel(sparkSession, logger, config, flowRecords)
- val orderedFlowRecords = filteredScored.orderBy(Score)
+ logger.info("Identifying outliers")
+ val scoredFlowRecords = model.score(sparkSession, flowRecords, config.precisionUtility)
- val mostSuspiciousFlowRecords =
- if (config.maxResults > 0) orderedFlowRecords.limit(config.maxResults) else orderedFlowRecords
+ val filteredScored = filterScoredRecords(scoredFlowRecords, config.threshold)
- val outputFlowRecords = mostSuspiciousFlowRecords.select(OutSchema: _*)
+ val orderedFlowRecords = filteredScored.orderBy(Score)
- val invalidFlowRecords = filterInvalidRecords(inputFlowRecords).select(InSchema: _*)
+ val mostSuspiciousFlowRecords =
+ if (config.maxResults > 0) orderedFlowRecords.limit(config.maxResults) else orderedFlowRecords
- SuspiciousConnectsAnalysisResults(outputFlowRecords, invalidFlowRecords)
+ val outputFlowRecords = mostSuspiciousFlowRecords.select(OutSchema: _*)
+ val invalidFlowRecords = filterInvalidRecords(inputFlowRecords).select(InSchema: _*)
+
+ Option(SuspiciousConnectsAnalysisResults(outputFlowRecords, invalidFlowRecords))
+ }
}
/**
@@ -177,4 +185,16 @@ object FlowSuspiciousConnectsAnalysis {
scoredFlowRecords.filter(filteredFlowRecordsFilter)
}
+ /**
+ * Validates incoming data matches required schema for model training and scoring.
+ *
+ * @param inputFlowRecords incoming data frame
+ * @return
+ */
+ def validateSchema(inputFlowRecords: DataFrame): Seq[String] = {
+
+ InputSchema.validate(inputFlowRecords.schema, FlowSuspiciousConnectsModel.ModelSchema)
+
+ }
+
}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-spot/blob/9c537a7a/spot-ml/src/main/scala/org/apache/spot/netflow/model/FlowSuspiciousConnectsModel.scala
----------------------------------------------------------------------
diff --git a/spot-ml/src/main/scala/org/apache/spot/netflow/model/FlowSuspiciousConnectsModel.scala b/spot-ml/src/main/scala/org/apache/spot/netflow/model/FlowSuspiciousConnectsModel.scala
index c29260a..6be11e1 100644
--- a/spot-ml/src/main/scala/org/apache/spot/netflow/model/FlowSuspiciousConnectsModel.scala
+++ b/spot-ml/src/main/scala/org/apache/spot/netflow/model/FlowSuspiciousConnectsModel.scala
@@ -141,7 +141,7 @@ object FlowSuspiciousConnectsModel {
val selectedRecords = inputRecords.select(ModelColumns: _*)
- val totalRecords = selectedRecords.unionAll(FlowFeedback.loadFeedbackDF(sparkSession,
+ val totalRecords = selectedRecords.union(FlowFeedback.loadFeedbackDF(sparkSession,
config.feedbackFile,
config.duplicationFactor))
http://git-wip-us.apache.org/repos/asf/incubator-spot/blob/9c537a7a/spot-ml/src/main/scala/org/apache/spot/proxy/ProxySuspiciousConnectsAnalysis.scala
----------------------------------------------------------------------
diff --git a/spot-ml/src/main/scala/org/apache/spot/proxy/ProxySuspiciousConnectsAnalysis.scala b/spot-ml/src/main/scala/org/apache/spot/proxy/ProxySuspiciousConnectsAnalysis.scala
index 90ac063..0fa2fd2 100644
--- a/spot-ml/src/main/scala/org/apache/spot/proxy/ProxySuspiciousConnectsAnalysis.scala
+++ b/spot-ml/src/main/scala/org/apache/spot/proxy/ProxySuspiciousConnectsAnalysis.scala
@@ -24,7 +24,7 @@ import org.apache.spark.sql.{DataFrame, SparkSession}
import org.apache.spot.SuspiciousConnects.SuspiciousConnectsAnalysisResults
import org.apache.spot.SuspiciousConnectsArgumentParser.SuspiciousConnectsConfig
import org.apache.spot.proxy.ProxySchema._
-import org.apache.spot.utilities.data.validation.{InvalidDataHandler => dataValidation}
+import org.apache.spot.utilities.data.validation.{InputSchema, InvalidDataHandler => dataValidation}
/**
* Run suspicious connections analysis on proxy data.
@@ -84,36 +84,45 @@ object ProxySuspiciousConnectsAnalysis {
* @param logger Logs execution progress, information and errors for user.
*/
def run(config: SuspiciousConnectsConfig, sparkSession: SparkSession, logger: Logger,
- inputProxyRecords: DataFrame): SuspiciousConnectsAnalysisResults = {
+ inputProxyRecords: DataFrame): Option[SuspiciousConnectsAnalysisResults] = {
logger.info("Starting proxy suspicious connects analysis.")
- val proxyRecords = filterRecords(inputProxyRecords)
- .select(InSchema: _*)
- .na.fill(DefaultUserAgent, Seq(UserAgent))
- .na.fill(DefaultResponseContentType, Seq(ResponseContentType))
+ logger.info("Validating schema...")
+ val schemaValidationResults = validateSchema(inputProxyRecords)
- logger.info("Fitting probabilistic model to data")
- val model = ProxySuspiciousConnectsModel.trainModel(sparkSession, logger, config, proxyRecords)
+ if (schemaValidationResults.length > InputSchema.ResponseDefaultSize) {
+ schemaValidationResults.foreach(logger.error(_))
- logger.info("Identifying outliers")
- val scoredProxyRecords = model.score(sparkSession, proxyRecords, config.precisionUtility)
+ None
+ } else {
+ val proxyRecords = filterRecords(inputProxyRecords)
+ .select(InSchema: _*)
+ .na.fill(DefaultUserAgent, Seq(UserAgent))
+ .na.fill(DefaultResponseContentType, Seq(ResponseContentType))
- // take the maxResults least probable events of probability below the threshold and sort
+ logger.info("Fitting probabilistic model to data")
+ val model = ProxySuspiciousConnectsModel.trainModel(sparkSession, logger, config, proxyRecords)
- val filteredScored = filterScoredRecords(scoredProxyRecords, config.threshold)
+ logger.info("Identifying outliers")
+ val scoredProxyRecords = model.score(sparkSession, proxyRecords, config.precisionUtility)
- val orderedProxyRecords = filteredScored.orderBy(Score)
+ // take the maxResults least probable events of probability below the threshold and sort
- val mostSuspiciousProxyRecords =
- if (config.maxResults > 0) orderedProxyRecords.limit(config.maxResults)
- else orderedProxyRecords
+ val filteredScored = filterScoredRecords(scoredProxyRecords, config.threshold)
- val outputProxyRecords = mostSuspiciousProxyRecords.select(OutSchema: _*)
+ val orderedProxyRecords = filteredScored.orderBy(Score)
- val invalidProxyRecords = filterInvalidRecords(inputProxyRecords).select(InSchema: _*)
+ val mostSuspiciousProxyRecords =
+ if (config.maxResults > 0) orderedProxyRecords.limit(config.maxResults)
+ else orderedProxyRecords
- SuspiciousConnectsAnalysisResults(outputProxyRecords, invalidProxyRecords)
+ val outputProxyRecords = mostSuspiciousProxyRecords.select(OutSchema: _*)
+
+ val invalidProxyRecords = filterInvalidRecords(inputProxyRecords).select(InSchema: _*)
+
+ Option(SuspiciousConnectsAnalysisResults(outputProxyRecords, invalidProxyRecords))
+ }
}
@@ -165,4 +174,16 @@ object ProxySuspiciousConnectsAnalysis {
scoredProxyRecords.filter(filteredProxyRecordsFilter)
}
+ /**
+ * Validates incoming data matches required schema for model training and scoring.
+ *
+ * @param inputProxyRecords incoming data frame
+ * @return
+ */
+ def validateSchema(inputProxyRecords: DataFrame): Seq[String] = {
+
+ InputSchema.validate(inputProxyRecords.schema, ProxySuspiciousConnectsModel.ModelSchema)
+
+ }
+
}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-spot/blob/9c537a7a/spot-ml/src/main/scala/org/apache/spot/proxy/ProxySuspiciousConnectsModel.scala
----------------------------------------------------------------------
diff --git a/spot-ml/src/main/scala/org/apache/spot/proxy/ProxySuspiciousConnectsModel.scala b/spot-ml/src/main/scala/org/apache/spot/proxy/ProxySuspiciousConnectsModel.scala
index 0cf006b..3ef60af 100644
--- a/spot-ml/src/main/scala/org/apache/spot/proxy/ProxySuspiciousConnectsModel.scala
+++ b/spot-ml/src/main/scala/org/apache/spot/proxy/ProxySuspiciousConnectsModel.scala
@@ -21,6 +21,7 @@ import org.apache.log4j.Logger
import org.apache.spark.broadcast.Broadcast
import org.apache.spark.rdd.RDD
import org.apache.spark.sql.functions._
+import org.apache.spark.sql.types.StructType
import org.apache.spark.sql.{DataFrame, Row, SparkSession}
import org.apache.spot.SuspiciousConnectsArgumentParser.SuspiciousConnectsConfig
import org.apache.spot.SuspiciousConnectsScoreFunction
@@ -100,6 +101,18 @@ object ProxySuspiciousConnectsModel {
3.0, 3.3, 3.6, 3.9, 4.2,
4.5, 4.8, 5.1, 5.4, Double.PositiveInfinity)
+ val ModelSchema = StructType(List(DateField,
+ TimeField,
+ ClientIPField,
+ HostField,
+ ReqMethodField,
+ UserAgentField,
+ ResponseContentTypeField,
+ RespCodeField,
+ FullURIField))
+
+ val ModelColumns = ModelSchema.fieldNames.toList.map(col)
+
/**
* Factory for ProxySuspiciousConnectsModel.
* Trains the model from the incoming DataFrame using the specified number of topics
@@ -121,9 +134,8 @@ object ProxySuspiciousConnectsModel {
val selectedRecords =
- inputRecords.select(Date, Time, ClientIP, Host, ReqMethod, UserAgent, ResponseContentType, RespCode, FullURI)
- .unionAll(ProxyFeedback.loadFeedbackDF(sparkSession, config.feedbackFile, config.duplicationFactor))
-
+ inputRecords.select(ModelColumns: _*)
+ .union(ProxyFeedback.loadFeedbackDF(sparkSession, config.feedbackFile, config.duplicationFactor))
val agentToCount: Map[String, Long] =
http://git-wip-us.apache.org/repos/asf/incubator-spot/blob/9c537a7a/spot-ml/src/main/scala/org/apache/spot/utilities/data/validation/InputSchema.scala
----------------------------------------------------------------------
diff --git a/spot-ml/src/main/scala/org/apache/spot/utilities/data/validation/InputSchema.scala b/spot-ml/src/main/scala/org/apache/spot/utilities/data/validation/InputSchema.scala
new file mode 100644
index 0000000..6f0df78
--- /dev/null
+++ b/spot-ml/src/main/scala/org/apache/spot/utilities/data/validation/InputSchema.scala
@@ -0,0 +1,48 @@
+package org.apache.spot.utilities.data.validation
+
+import org.apache.spark.sql.types.{DataType, StructType}
+
+import scala.collection.mutable.ListBuffer
+
+
+/**
+ * Input schema routines
+ */
+object InputSchema {
+
+ // Response from validate will contains always at least 1 element. 1 message means no errors.
+ val ResponseDefaultSize = 1
+
+ /**
+ * Validate the incoming data schema matches the schema required for model creation and scoring.
+ *
+ * @param inSchema incoming data frame
+ * @param expectedSchema schema expected by model training and scoring methods
+ * @return
+ */
+ def validate(inSchema: StructType, expectedSchema: StructType): Seq[String] = {
+ val response: ListBuffer[String] = ListBuffer("Schema not compatible:")
+
+ // reduce schema from struct field to only field name and type
+ val inSchemaMap: Map[String, DataType] = inSchema.map(field => (field.name -> field.dataType)).toMap
+
+ expectedSchema
+ .map(field => (field.name, field.dataType))
+ .foreach({ case (expectedFieldName: String, expectedDataType: DataType) => {
+
+ val inFieldDataType = inSchemaMap.getOrElse(expectedFieldName, None)
+
+ inFieldDataType match {
+ case None => response.append(s"Field $expectedFieldName is not present. $expectedFieldName is required for " +
+ s"model training and scoring.")
+ case inputDataType: DataType =>
+ if (inputDataType != expectedDataType)
+ response.append(s"Field $expectedFieldName type ${inputDataType.typeName} is not the expected type " +
+ s"${expectedDataType.typeName}")
+ }
+ }
+ })
+
+ response
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-spot/blob/9c537a7a/spot-ml/src/test/scala/org/apache/spot/dns/DNSSuspiciousConnectsAnalysisTest.scala
----------------------------------------------------------------------
diff --git a/spot-ml/src/test/scala/org/apache/spot/dns/DNSSuspiciousConnectsAnalysisTest.scala b/spot-ml/src/test/scala/org/apache/spot/dns/DNSSuspiciousConnectsAnalysisTest.scala
index 5ceccaa..a940ea6 100644
--- a/spot-ml/src/test/scala/org/apache/spot/dns/DNSSuspiciousConnectsAnalysisTest.scala
+++ b/spot-ml/src/test/scala/org/apache/spot/dns/DNSSuspiciousConnectsAnalysisTest.scala
@@ -39,6 +39,15 @@ case class DNSInput(frame_time: String,
dns_qry_type: Int,
dns_qry_rcode: Int)
+case class DNSInvalidSchema(frame_time: String,
+ unix_tstamp: Double,
+ frame_len: Int,
+ ip_dst: String,
+ dns_qry_name: String,
+ dns_qry_class: String,
+ dns_qry_type: String,
+ dns_qry_rcode: String)
+
class DNSSuspiciousConnectsAnalysisTest extends TestingSparkContextFlatSpec with Matchers {
val emTestConfig = SuspiciousConnectsConfig(analysis = "dns",
@@ -101,6 +110,8 @@ class DNSSuspiciousConnectsAnalysisTest extends TestingSparkContextFlatSpec with
val SuspiciousConnectsAnalysisResults(scoredData, _) =
DNSSuspiciousConnectsAnalysis.run(emTestConfig, sparkSession, logger, data)
+ .getOrElse(SuspiciousConnectsAnalysisResults(sparkSession.sqlContext.emptyDataFrame,
+ sparkSession.sqlContext.emptyDataFrame))
val anomalyScore = scoredData.filter(scoredData(FrameLength) === 1).first().getAs[Double](Score)
val typicalScores = scoredData.filter(scoredData(FrameLength) === 168).collect().map(_.getAs[Double](Score))
@@ -123,8 +134,10 @@ class DNSSuspiciousConnectsAnalysisTest extends TestingSparkContextFlatSpec with
val typicalRecord = DNSInput("May 20 2016 02:10:25.970987000 PDT", 1463735425L, 168, "172.16.9.132", "122.2o7.turner.com", "0x00000001", 1, 0)
val data = sparkSession.createDataFrame(Seq(anomalousRecord, typicalRecord, typicalRecord, typicalRecord, typicalRecord))
- val SuspiciousConnectsAnalysisResults(scoredData, _) = DNSSuspiciousConnectsAnalysis.run(onlineTestConfig,
- sparkSession, logger, data)
+ val SuspiciousConnectsAnalysisResults(scoredData, _) =
+ DNSSuspiciousConnectsAnalysis.run(onlineTestConfig, sparkSession, logger, data)
+ .getOrElse(SuspiciousConnectsAnalysisResults(sparkSession.sqlContext.emptyDataFrame,
+ sparkSession.sqlContext.emptyDataFrame))
val anomalyScore = scoredData.filter(scoredData(FrameLength) === 1).first().getAs[Double](Score)
val typicalScores = scoredData.filter(scoredData(FrameLength) === 168).collect().map(_.getAs[Double](Score))
@@ -284,6 +297,26 @@ class DNSSuspiciousConnectsAnalysisTest extends TestingSparkContextFlatSpec with
Math.abs(typicalScores(3) - 0.8d) should be <= 0.01d
}
+ it should "return None when input data frame doesn't matches expected schema" in {
+ val logger = LogManager.getLogger("SuspiciousConnectsAnalysis")
+ logger.setLevel(Level.WARN)
+
+ val anomalousRecord = DNSInvalidSchema("May 20 2016 02:10:25.970987000 PDT", 1463735425d, 1, "172.16.9.132",
+ "122.2o7.turner.com", "0x00000001", "null", "null")
+ val data = sparkSession.createDataFrame(Seq(anomalousRecord, anomalousRecord, anomalousRecord, anomalousRecord, anomalousRecord))
+
+ val result: Option[SuspiciousConnectsAnalysisResults] =
+ DNSSuspiciousConnectsAnalysis.run(emTestConfig, sparkSession, logger, data)
+
+ val none = result match {
+ case None => true
+ case Some(_) => false
+ }
+
+ none shouldBe true
+
+ }
+
"filterRecords" should "return data set without garbage" in {
val cleanedDNSRecords = DNSSuspiciousConnectsAnalysis.filterRecords(testDNSRecords.inputDNSRecordsDF)
@@ -309,6 +342,25 @@ class DNSSuspiciousConnectsAnalysisTest extends TestingSparkContextFlatSpec with
scoredDNSRecords.count should be(2)
}
+ "validateSchema" should "return a Seq[String] of size > 1 when passing an invalid schema" in {
+ val anomalousRecord = DNSInvalidSchema("May 20 2016 02:10:25.970987000 PDT", 1463735425d, 1, "172.16.9.132",
+ "122.2o7.turner.com", "0x00000001", "null", "null")
+ val data = sparkSession.createDataFrame(Seq(anomalousRecord, anomalousRecord, anomalousRecord, anomalousRecord, anomalousRecord))
+
+ val results = DNSSuspiciousConnectsAnalysis.validateSchema(data)
+
+ results.length should be > 1
+ }
+
+ it should "return a Seq[String] of size 1 when passing a valid schema" in {
+ val typicalRecord = DNSInput("May 20 2016 02:10:25.970987000 PDT", 1463735425L, 168, "172.16.9.132", "122.2o7.turner.com", "0x00000001", 1, 0)
+ val data = sparkSession.createDataFrame(Seq(typicalRecord, typicalRecord, typicalRecord, typicalRecord))
+
+ val results = DNSSuspiciousConnectsAnalysis.validateSchema(data)
+
+ results.length shouldBe 1
+ }
+
def testDNSRecords = new {
http://git-wip-us.apache.org/repos/asf/incubator-spot/blob/9c537a7a/spot-ml/src/test/scala/org/apache/spot/netflow/FlowRecord.scala
----------------------------------------------------------------------
diff --git a/spot-ml/src/test/scala/org/apache/spot/netflow/FlowRecord.scala b/spot-ml/src/test/scala/org/apache/spot/netflow/FlowRecord.scala
index 7c1ae86..19e51be 100644
--- a/spot-ml/src/test/scala/org/apache/spot/netflow/FlowRecord.scala
+++ b/spot-ml/src/test/scala/org/apache/spot/netflow/FlowRecord.scala
@@ -37,3 +37,21 @@ case class FlowRecord(treceived: String,
ibyt: Long,
opkt: Long,
obyt: Long)
+
+case class FlowInvalidRecord(treceived: String,
+ tryear: Int,
+ trmonth: Int,
+ trday: Int,
+ trhour: Int,
+ trminute: Int,
+ trsec: Int,
+ tdur: Int,
+ sip: String,
+ dip: String,
+ sport: Int,
+ dport: Int,
+ proto: String,
+ ipkt: String,
+ ibyt: String,
+ opkt: String,
+ obyt: String)
http://git-wip-us.apache.org/repos/asf/incubator-spot/blob/9c537a7a/spot-ml/src/test/scala/org/apache/spot/netflow/FlowSuspiciousConnectsAnalysisTest.scala
----------------------------------------------------------------------
diff --git a/spot-ml/src/test/scala/org/apache/spot/netflow/FlowSuspiciousConnectsAnalysisTest.scala b/spot-ml/src/test/scala/org/apache/spot/netflow/FlowSuspiciousConnectsAnalysisTest.scala
index 9310390..7a15295 100644
--- a/spot-ml/src/test/scala/org/apache/spot/netflow/FlowSuspiciousConnectsAnalysisTest.scala
+++ b/spot-ml/src/test/scala/org/apache/spot/netflow/FlowSuspiciousConnectsAnalysisTest.scala
@@ -92,8 +92,10 @@ class FlowSuspiciousConnectsAnalysisTest extends TestingSparkContextFlatSpec wit
val data = sparkSession.createDataFrame(Seq(anomalousRecord, typicalRecord, typicalRecord, typicalRecord, typicalRecord, typicalRecord,
typicalRecord, typicalRecord, typicalRecord, typicalRecord))
- val SuspiciousConnectsAnalysisResults(scoredData, _) = FlowSuspiciousConnectsAnalysis.run(emTestConfig,
- sparkSession, logger, data)
+ val SuspiciousConnectsAnalysisResults(scoredData, _) =
+ FlowSuspiciousConnectsAnalysis.run(emTestConfig, sparkSession, logger, data)
+ .getOrElse(SuspiciousConnectsAnalysisResults(sparkSession.sqlContext.emptyDataFrame,
+ sparkSession.sqlContext.emptyDataFrame))
val anomalyScore = scoredData.filter(scoredData(Hour) === 0).first().getAs[Double](Score)
val typicalScores = scoredData.filter(scoredData(Hour) === 13).collect().map(_.getAs[Double](Score))
@@ -124,8 +126,10 @@ class FlowSuspiciousConnectsAnalysisTest extends TestingSparkContextFlatSpec wit
val data = sparkSession.createDataFrame(Seq(anomalousRecord, typicalRecord, typicalRecord, typicalRecord, typicalRecord, typicalRecord,
typicalRecord, typicalRecord, typicalRecord, typicalRecord))
- val SuspiciousConnectsAnalysisResults(scoredData, _) = FlowSuspiciousConnectsAnalysis.run(onlineTestConfig,
- sparkSession, logger, data)
+ val SuspiciousConnectsAnalysisResults(scoredData, _) =
+ FlowSuspiciousConnectsAnalysis.run(onlineTestConfig, sparkSession, logger, data)
+ .getOrElse(SuspiciousConnectsAnalysisResults(sparkSession.sqlContext.emptyDataFrame,
+ sparkSession.sqlContext.emptyDataFrame))
val anomalyScore = scoredData.filter(scoredData(Hour) === 0).first().getAs[Double](Score)
val typicalScores = scoredData.filter(scoredData(Hour) === 13).collect().map(_.getAs[Double](Score))
@@ -239,6 +243,27 @@ class FlowSuspiciousConnectsAnalysisTest extends TestingSparkContextFlatSpec wit
}
+ it should "return None when input data frame doesn't matches expected schema" in {
+ val logger = LogManager.getLogger("SuspiciousConnectsAnalysis")
+ logger.setLevel(Level.OFF)
+
+ val anomalousRecord = FlowInvalidRecord("2016-05-05 00:11:01", 2016, 5, 5, 0, 0, 1, 972, "172.16.0.129", "10.0" +
+ ".2.202", 1024, 80, "TCP", "39l", "12522l", "0l", "0l")
+
+ val data = sparkSession.createDataFrame(Seq(anomalousRecord, anomalousRecord, anomalousRecord, anomalousRecord))
+
+ val result =
+ FlowSuspiciousConnectsAnalysis.run(emTestConfig, sparkSession, logger, data)
+
+ val none = result match {
+ case None => true
+ case Some(_) => false
+ }
+
+ none shouldBe true
+
+ }
+
"filterRecords" should "return data set without garbage" in {
val cleanedFlowRecords = FlowSuspiciousConnectsAnalysis
@@ -267,6 +292,29 @@ class FlowSuspiciousConnectsAnalysisTest extends TestingSparkContextFlatSpec wit
scoredFlowRecords.count should be(2)
}
+ "validateSchema" should "return a Seq[String] of size > 1 when passing an invalid schema" in {
+ val anomalousRecord = FlowInvalidRecord("2016-05-05 00:11:01", 2016, 5, 5, 0, 0, 1, 972, "172.16.0.129", "10.0" +
+ ".2.202", 1024, 80, "TCP", "39l", "12522l", "0l", "0l")
+
+ val data = sparkSession.createDataFrame(Seq(anomalousRecord, anomalousRecord, anomalousRecord, anomalousRecord))
+
+ val results = FlowSuspiciousConnectsAnalysis.validateSchema(data)
+
+ results.length should be > 1
+ }
+
+ it should "return a Seq[String] of size 1 when passing a valid schema" in {
+ val typicalRecord = FlowRecord("2016-05-05 13:54:58", 2016, 5, 5, 13, 54, 58, 0.972f, "172.16.0.129", "10.0.2" +
+ ".202", 1024, 80, "TCP", 39, 12522, 0, 0)
+
+ val data = sparkSession.createDataFrame(Seq(typicalRecord, typicalRecord, typicalRecord, typicalRecord,
+ typicalRecord, typicalRecord, typicalRecord, typicalRecord, typicalRecord))
+
+ val results = FlowSuspiciousConnectsAnalysis.validateSchema(data)
+
+
+ }
+
def testFlowRecords = new {
val inputFlowRecordsRDD = sparkSession.sparkContext.parallelize(wrapRefArray(Array(
http://git-wip-us.apache.org/repos/asf/incubator-spot/blob/9c537a7a/spot-ml/src/test/scala/org/apache/spot/proxy/ProxySuspiciousConnectsAnalysisTest.scala
----------------------------------------------------------------------
diff --git a/spot-ml/src/test/scala/org/apache/spot/proxy/ProxySuspiciousConnectsAnalysisTest.scala b/spot-ml/src/test/scala/org/apache/spot/proxy/ProxySuspiciousConnectsAnalysisTest.scala
index e7dfd04..8ec75f2 100644
--- a/spot-ml/src/test/scala/org/apache/spot/proxy/ProxySuspiciousConnectsAnalysisTest.scala
+++ b/spot-ml/src/test/scala/org/apache/spot/proxy/ProxySuspiciousConnectsAnalysisTest.scala
@@ -47,6 +47,26 @@ case class ProxyInput(p_date: String,
csbytes: Int,
fulluri: String)
+case class ProxyInvalidInput(p_date: String,
+ p_time: String,
+ clientip: String,
+ host: Double,
+ reqmethod: String,
+ useragent: String,
+ resconttype: Int,
+ duration: Int,
+ username: String,
+ webcat: String,
+ referer: String,
+ respcode: String,
+ uriport: Int,
+ uripath: String,
+ uriquery: String,
+ serverip: String,
+ scbytes: Int,
+ csbytes: Int,
+ fulluri: Double)
+
class ProxySuspiciousConnectsAnalysisTest extends TestingSparkContextFlatSpec with Matchers {
@@ -107,8 +127,10 @@ class ProxySuspiciousConnectsAnalysisTest extends TestingSparkContextFlatSpec wi
val data = sparkSession.createDataFrame(Seq(anomalousRecord, typicalRecord, typicalRecord, typicalRecord, typicalRecord,
typicalRecord, typicalRecord, typicalRecord, typicalRecord, typicalRecord))
- val SuspiciousConnectsAnalysisResults(scoredData, _) = ProxySuspiciousConnectsAnalysis.run(emTestConfigProxy,
- sparkSession, logger, data)
+ val SuspiciousConnectsAnalysisResults(scoredData, _) =
+ ProxySuspiciousConnectsAnalysis.run(emTestConfigProxy, sparkSession, logger, data)
+ .getOrElse(SuspiciousConnectsAnalysisResults(sparkSession.sqlContext.emptyDataFrame,
+ sparkSession.sqlContext.emptyDataFrame))
val anomalyScore = scoredData.filter(scoredData(Host) === "intel.com").first().getAs[Double](Score)
val typicalScores = scoredData.filter(scoredData(Host) === "maw.bronto.com").collect().map(_.getAs[Double](Score))
@@ -152,6 +174,8 @@ class ProxySuspiciousConnectsAnalysisTest extends TestingSparkContextFlatSpec wi
val SuspiciousConnectsAnalysisResults(scoredData, _) =
ProxySuspiciousConnectsAnalysis.run(onlineTestConfigProxy, sparkSession, logger, data)
+ .getOrElse(SuspiciousConnectsAnalysisResults(sparkSession.sqlContext.emptyDataFrame,
+ sparkSession.sqlContext.emptyDataFrame))
val anomalyScore = scoredData.filter(scoredData(Host) === "intel.com").first().getAs[Double](Score)
val typicalScores = scoredData.filter(scoredData(Host) === "maw.bronto.com").collect().map(_.getAs[Double](Score))
@@ -202,6 +226,32 @@ class ProxySuspiciousConnectsAnalysisTest extends TestingSparkContextFlatSpec wi
Math.abs(typicalScores(8) - 0.9d) should be <= 0.01d
}
+ it should "return None when input data frame doesn't matches expected schema" in {
+ val logger = LogManager.getLogger("SuspiciousConnectsAnalysis")
+ logger.setLevel(Level.WARN)
+
+
+ val anomalousRecord = ProxyInvalidInput("2016-10-03", "04:57:36", "127.0.0.1", 0.0d, "PUT",
+ "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.116 Safari/537.36",
+ 1, 230, "-", "Technology/Internet", "http://www.spoonflower.com/tags/color", "202", 80,
+ "/sites/c37i4q22szvir8ga3m8mtxaft7gwnm5fio8hfxo35mu81absi1/carts/4b3a313d-50f6-4117-8ffd-4e804fd354ef/fiddle",
+ "-", "127.0.0.1", 338, 647,
+ 1.0d)
+
+ val data = sparkSession.createDataFrame(Seq(anomalousRecord, anomalousRecord, anomalousRecord, anomalousRecord,
+ anomalousRecord))
+
+ val results =
+ ProxySuspiciousConnectsAnalysis.run(emTestConfigProxy, sparkSession, logger, data)
+
+ val none = results match {
+ case None => true
+ case Some(_) => false
+ }
+
+ none shouldBe true
+ }
+
"filterRecords" should "return data without garbage" in {
val cleanedProxyRecords = ProxySuspiciousConnectsAnalysis
@@ -232,6 +282,39 @@ class ProxySuspiciousConnectsAnalysisTest extends TestingSparkContextFlatSpec wi
}
+ "validateSchema" should "return a Seq[String] of size > 1 when passing an invalid schema" in {
+ val anomalousRecord = ProxyInvalidInput("2016-10-03", "04:57:36", "127.0.0.1", 0.0d, "PUT",
+ "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.116 Safari/537.36",
+ 1, 230, "-", "Technology/Internet", "http://www.spoonflower.com/tags/color", "202", 80,
+ "/sites/c37i4q22szvir8ga3m8mtxaft7gwnm5fio8hfxo35mu81absi1/carts/4b3a313d-50f6-4117-8ffd-4e804fd354ef/fiddle",
+ "-", "127.0.0.1", 338, 647,
+ 1.0d)
+
+ val data = sparkSession.createDataFrame(Seq(anomalousRecord, anomalousRecord, anomalousRecord, anomalousRecord,
+ anomalousRecord))
+
+ val results = ProxySuspiciousConnectsAnalysis.validateSchema(data)
+
+ results.length should be > 1
+
+ }
+
+ it should "return a Seq[String] of size 1 when passing a valid schema" in {
+ val typicalRecord = ProxyInput("2016-10-03", "04:57:36", "127.0.0.1", "maw.bronto.com", "PUT",
+ "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.116 Safari/537.36",
+ "text/plain", 230, "-", "Technology/Internet", "http://www.spoonflower.com/tags/color", "202", 80,
+ "/sites/c37i4q22szvir8ga3m8mtxaft7gwnm5fio8hfxo35mu81absi1/carts/4b3a313d-50f6-4117-8ffd-4e804fd354ef/fiddle",
+ "-", "127.0.0.1", 338, 647,
+ "maw.bronto.com/sites/c37i4q22szvir8ga3m8mtxaft7gwnm5fio8hfxo35mu81absi1/carts/4b3a313d-50f6-4117-8ffd-4e804fd354ef/fiddle")
+
+ val data = sparkSession.createDataFrame(Seq(typicalRecord, typicalRecord, typicalRecord))
+
+ val results = ProxySuspiciousConnectsAnalysis.validateSchema(data)
+
+ results.length shouldBe 1
+
+ }
+
def anomalousAndTypicalRecords(): (ProxyInput, ProxyInput) = {
val anomalousRecord = ProxyInput("2016-10-03", "04:57:36", "127.0.0.1", "intel.com", "PUT",
"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.116 Safari/537.36",
http://git-wip-us.apache.org/repos/asf/incubator-spot/blob/9c537a7a/spot-ml/src/test/scala/org/apache/spot/utilities/data/validation/InputSchemaTest.scala
----------------------------------------------------------------------
diff --git a/spot-ml/src/test/scala/org/apache/spot/utilities/data/validation/InputSchemaTest.scala b/spot-ml/src/test/scala/org/apache/spot/utilities/data/validation/InputSchemaTest.scala
new file mode 100644
index 0000000..13611d1
--- /dev/null
+++ b/spot-ml/src/test/scala/org/apache/spot/utilities/data/validation/InputSchemaTest.scala
@@ -0,0 +1,53 @@
+package org.apache.spot.utilities.data.validation
+
+import org.apache.spark.sql.types._
+import org.scalatest.{FlatSpec, Matchers}
+
+class InputSchemaTest extends FlatSpec with Matchers {
+
+ "validate" should "return a Seq[String] of size 1 when incoming schema is valid" in {
+
+ val incomingSchema = StructType(List(StructField("ip", StringType),
+ StructField("ibyt", LongType),
+ StructField("host", StringType),
+ StructField("score", FloatType)))
+
+ val modelSchema = StructType(List(StructField("ip", StringType),
+ StructField("ibyt", LongType),
+ StructField("host", StringType)))
+
+ val results = InputSchema.validate(incomingSchema, modelSchema)
+
+ results.length shouldBe 1
+ }
+
+ it should "return a Seq[String] of size > 1 when incoming schema is not valid due to type mismatch" in {
+ val incomingSchema = StructType(List(StructField("ip", StringType),
+ StructField("ibyt", StringType),
+ StructField("host", IntegerType),
+ StructField("score", FloatType)))
+
+ val modelSchema = StructType(List(StructField("ip", StringType),
+ StructField("ibyt", LongType),
+ StructField("host", StringType)))
+
+ val results = InputSchema.validate(incomingSchema, modelSchema)
+
+ results.length shouldBe 3
+ }
+
+ it should "return a Seq[String] of size > 1 when incoming schema is not valid due to required field is missing" in {
+
+ val incomingSchema = StructType(List(StructField("ip", StringType),
+ StructField("ibyt", LongType),
+ StructField("score", FloatType)))
+
+ val modelSchema = StructType(List(StructField("ip", StringType),
+ StructField("ibyt", LongType),
+ StructField("host", StringType)))
+
+ val results = InputSchema.validate(incomingSchema, modelSchema)
+
+ results.length shouldBe 2
+ }
+}