Github user brkyvz commented on a diff in the pull request:

    https://github.com/apache/spark/pull/18199#discussion_r121191644
  
    --- Diff: 
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/RateSourceProvider.scala
 ---
    @@ -0,0 +1,279 @@
    +/*
    + * 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.spark.sql.execution.streaming
    +
    +import java.io._
    +import java.nio.charset.StandardCharsets
    +import java.util.concurrent.TimeUnit
    +
    +import org.apache.commons.io.IOUtils
    +
    +import org.apache.spark.internal.Logging
    +import org.apache.spark.network.util.JavaUtils
    +import org.apache.spark.sql.{DataFrame, SQLContext}
    +import org.apache.spark.sql.catalyst.InternalRow
    +import org.apache.spark.sql.catalyst.util.{CaseInsensitiveMap, 
DateTimeUtils}
    +import org.apache.spark.sql.sources.{DataSourceRegister, 
StreamSourceProvider}
    +import org.apache.spark.sql.types._
    +import org.apache.spark.util.{ManualClock, SystemClock}
    +
    +/**
    + *  A source that generates increment long values with timestamps. Each 
generated row has two
    + *  columns: a timestamp column for the generated time and an auto 
increment long column starting
    + *  with 0L.
    + *
    + *  This source supports the following options:
    + *  - `tuplesPerSecond` (e.g. 100, default: 1): How many tuples should be 
generated per second.
    + *  - `rampUpTime` (e.g. 5s, default: 0s): How long to ramp up before the 
generating speed
    + *    becomes `tuplesPerSecond`. Using finer granularities than seconds 
will be truncated to integer
    + *    seconds.
    + *  - `numPartitions` (e.g. 10, default: Spark's default parallelism): The 
partition number for the
    + *    generated tuples. The source will try its best to reach 
`tuplesPerSecond`, but the query may
    + *    be resource constrained, and `numPartitions` can be tweaked to help 
reach the desired speed.
    + */
    +class RateSourceProvider extends StreamSourceProvider with 
DataSourceRegister {
    +
    +  override def sourceSchema(
    +      sqlContext: SQLContext,
    +      schema: Option[StructType],
    +      providerName: String,
    +      parameters: Map[String, String]): (String, StructType) =
    +    (shortName(), RateSourceProvider.SCHEMA)
    +
    +  override def createSource(
    +      sqlContext: SQLContext,
    +      metadataPath: String,
    +      schema: Option[StructType],
    +      providerName: String,
    +      parameters: Map[String, String]): Source = {
    +    val params = CaseInsensitiveMap(parameters)
    +
    +    val tuplesPerSecond = 
params.get("tuplesPerSecond").map(_.toLong).getOrElse(1L)
    +    if (tuplesPerSecond <= 0) {
    +      throw new IllegalArgumentException(
    +        s"Invalid value '${params("tuplesPerSecond")}'. The option 
'tuplesPerSecond' " +
    +          "must be positive")
    +    }
    +
    +    val rampUpTimeSeconds =
    +      
params.get("rampUpTime").map(JavaUtils.timeStringAsSec(_)).getOrElse(0L)
    +    if (rampUpTimeSeconds < 0) {
    +      throw new IllegalArgumentException(
    +        s"Invalid value '${params("rampUpTime")}'. The option 'rampUpTime' 
" +
    +          "must not be negative")
    +    }
    +
    +    val numPartitions = params.get("numPartitions").map(_.toInt).getOrElse(
    +      sqlContext.sparkContext.defaultParallelism)
    +    if (numPartitions <= 0) {
    +      throw new IllegalArgumentException(
    +        s"Invalid value '${params("numPartitions")}'. The option 
'numPartitions' " +
    +          "must be positive")
    +    }
    +
    +    new RateStreamSource(
    +      sqlContext,
    +      metadataPath,
    +      tuplesPerSecond,
    +      rampUpTimeSeconds,
    +      numPartitions,
    +      params.get("useManualClock").map(_.toBoolean).getOrElse(false) // 
Only for testing
    +    )
    +  }
    +  override def shortName(): String = "rate"
    +}
    +
    +object RateSourceProvider {
    +  val SCHEMA =
    +    StructType(StructField("timestamp", TimestampType) :: 
StructField("value", LongType) :: Nil)
    +
    +  val VERSION = 1
    +}
    +
    +class RateStreamSource(
    +    sqlContext: SQLContext,
    +    metadataPath: String,
    +    tuplesPerSecond: Long,
    +    rampUpTimeSeconds: Long,
    +    numPartitions: Int,
    +    useManualClock: Boolean) extends Source with Logging {
    +
    +  import RateSourceProvider._
    +  import RateStreamSource._
    +
    +  val clock = if (useManualClock) new ManualClock else new SystemClock
    +
    +  private val maxSeconds = Long.MaxValue / tuplesPerSecond
    +
    +  if (rampUpTimeSeconds > maxSeconds) {
    +    throw new ArithmeticException(
    +      s"Integer overflow. Max offset with $tuplesPerSecond 
tuplesPerSecond" +
    +        s" is $maxSeconds, but 'rampUpTimeSeconds' is $rampUpTimeSeconds.")
    +  }
    +
    +  private val startTimeMs = {
    +    val metadataLog =
    +      new HDFSMetadataLog[LongOffset](sqlContext.sparkSession, 
metadataPath) {
    +        override def serialize(metadata: LongOffset, out: OutputStream): 
Unit = {
    +          val writer = new BufferedWriter(new OutputStreamWriter(out, 
StandardCharsets.UTF_8))
    +          writer.write("v" + VERSION + "\n")
    +          writer.write(metadata.json)
    +          writer.flush
    +        }
    +
    +        override def deserialize(in: InputStream): LongOffset = {
    +          val content = IOUtils.toString(new InputStreamReader(in, 
StandardCharsets.UTF_8))
    +          // HDFSMetadataLog guarantees that it never creates a partial 
file.
    +          assert(content.length != 0)
    +          if (content(0) == 'v') {
    +            val indexOfNewLine = content.indexOf("\n")
    +            if (indexOfNewLine > 0) {
    +              val version = parseVersion(content.substring(0, 
indexOfNewLine), VERSION)
    +              LongOffset(SerializedOffset(content.substring(indexOfNewLine 
+ 1)))
    +            } else {
    +              throw new IllegalStateException(
    +                s"Log file was malformed: failed to detect the log file 
version line.")
    +            }
    +          } else {
    +            throw new IllegalStateException(
    +              s"Log file was malformed: failed to detect the log file 
version line.")
    +          }
    +        }
    +      }
    +
    +    metadataLog.get(0).getOrElse {
    +      val offset = LongOffset(clock.getTimeMillis())
    +      metadataLog.add(0, offset)
    +      logInfo(s"Start time: $offset")
    +      offset
    +    }.offset
    +  }
    +
    +  /** When the system time runs backward, "lastTimeMs" will make sure we 
are still monotonic. */
    +  @volatile private var lastTimeMs = startTimeMs
    +
    +  override def schema: StructType = RateSourceProvider.SCHEMA
    +
    +  override def getOffset: Option[Offset] = {
    +    val now = clock.getTimeMillis()
    +    if (lastTimeMs < now) {
    +      lastTimeMs = now
    +    }
    +    Some(LongOffset(TimeUnit.MILLISECONDS.toSeconds(lastTimeMs - 
startTimeMs)))
    +  }
    +
    +  override def getBatch(start: Option[Offset], end: Offset): DataFrame = {
    +    val startSeconds = 
start.flatMap(LongOffset.convert(_).map(_.offset)).getOrElse(0L)
    +    val endSeconds = LongOffset.convert(end).map(_.offset).getOrElse(0L)
    +    assert(startSeconds <= endSeconds, s"startSeconds($startSeconds) > 
endSeconds($endSeconds)")
    +    if (endSeconds > maxSeconds) {
    +      throw new ArithmeticException("Integer overflow. Max offset with " +
    +        s"$tuplesPerSecond tuplesPerSecond is $maxSeconds, but it's 
$endSeconds now.")
    +    }
    +    // Fix "lastTimeMs" for recovery
    +    if (lastTimeMs < TimeUnit.SECONDS.toMillis(endSeconds) + startTimeMs) {
    +      lastTimeMs = TimeUnit.SECONDS.toMillis(endSeconds) + startTimeMs
    +    }
    +    val rangeStart = valueAtSecond(startSeconds, tuplesPerSecond, 
rampUpTimeSeconds)
    +    val rangeEnd = valueAtSecond(endSeconds, tuplesPerSecond, 
rampUpTimeSeconds)
    +    logDebug(s"startSeconds: $startSeconds, endSeconds: $endSeconds, " +
    +      s"rangeStart: $rangeStart, rangeEnd: $rangeEnd")
    +
    +    if (rangeStart == rangeEnd) {
    +      return 
sqlContext.internalCreateDataFrame(sqlContext.sparkContext.emptyRDD, schema)
    +    }
    +
    +    val localStartTimeMs = startTimeMs + 
TimeUnit.SECONDS.toMillis(startSeconds)
    +    val timeIntervalSizeMs = TimeUnit.SECONDS.toMillis(endSeconds - 
startSeconds)
    +
    +    val func =
    +      if (timeIntervalSizeMs < rangeEnd - rangeStart) {
    +        // Different rows may have the same timestamp
    +        val valueSizePerMs = (rangeEnd - rangeStart) / timeIntervalSizeMs
    +        val remainderValue = (rangeEnd - rangeStart) % timeIntervalSizeMs
    +
    +        (v: Long) => {
    +          val relativeValue = v - rangeStart
    +          val relativeMs = {
    +            // Increase the timestamp per "valueSizePerMs + 1" values 
before
    +            // "(valueSizePerMs + 1) * remainderValue", and increase the 
timestamp per
    +            // "valueSizePerMs" values for remaining values.
    +
    +            // The following condition is the same as
    +            // "relativeValue < (valueSizePerMs + 1) * remainderValue", 
just rewrite it to avoid
    +            // overflow.
    +            if (relativeValue - remainderValue < valueSizePerMs * 
remainderValue) {
    --- End diff --
    
    can we add parenthesis around `relativeValue - remainderValue`?


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastruct...@apache.org or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscr...@spark.apache.org
For additional commands, e-mail: reviews-h...@spark.apache.org

Reply via email to