You are viewing a plain text version of this content. The canonical link for it is here.
Posted to reviews@spark.apache.org by harishreedharan <gi...@git.apache.org> on 2014/05/17 02:54:30 UTC

[GitHub] spark pull request: SPARK-1729. Make Flume pull data from source, ...

GitHub user harishreedharan opened a pull request:

    https://github.com/apache/spark/pull/807

    SPARK-1729. Make Flume pull data from source, rather than the current pu...

    ...sh model
    
    Currently Spark uses Flume's internal Avro Protocol to ingest data from Flume. If the executor running the
    receiver fails, it currently has to be restarted on the same node to be able to receive data.
    
    This commit adds a new Sink which can be deployed to a Flume agent. This sink can be polled by a new
    DStream that is also included in this commit. This model ensures that data can be pulled into Spark from
    Flume even if the receiver is restarted on a new node. This also allows the receiver to receive data on
    multiple threads for better performance.

You can merge this pull request into a Git repository by running:

    $ git pull https://github.com/harishreedharan/spark master

Alternatively you can review and apply these changes as the patch at:

    https://github.com/apache/spark/pull/807.patch

To close this pull request, make a commit to your master/trunk branch
with (at least) the following in the commit message:

    This closes #807
    
----
commit 6d6776a45f30e3594a15bda2582f99819c28a583
Author: Hari Shreedharan <hs...@apache.org>
Date:   2014-05-09T06:16:56Z

    SPARK-1729. Make Flume pull data from source, rather than the current push model
    
    Currently Spark uses Flume's internal Avro Protocol to ingest data from Flume. If the executor running the
    receiver fails, it currently has to be restarted on the same node to be able to receive data.
    
    This commit adds a new Sink which can be deployed to a Flume agent. This sink can be polled by a new
    DStream that is also included in this commit. This model ensures that data can be pulled into Spark from
    Flume even if the receiver is restarted on a new node. This also allows the receiver to receive data on
    multiple threads for better performance.

----


---
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 infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] spark pull request: SPARK-1729. Make Flume pull data from source, ...

Posted by joyyoj <gi...@git.apache.org>.
Github user joyyoj commented on a diff in the pull request:

    https://github.com/apache/spark/pull/807#discussion_r13740432
  
    --- Diff: external/flume/src/main/scala/org/apache/spark/streaming/flume/EventTransformer.scala ---
    @@ -0,0 +1,72 @@
    +/*
    + * 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.streaming.flume
    +
    +import java.io.{ObjectOutput, ObjectInput}
    +
    +import scala.collection.JavaConversions._
    +
    +import org.apache.spark.util.Utils
    +import org.apache.spark.Logging
    +
    +/**
    + * A simple object that provides the implementation of readExternal and writeExternal for both
    + * the wrapper classes for Flume-style Events.
    + */
    +object EventTransformer extends Logging {
    +  def readExternal(in: ObjectInput): (java.util.HashMap[CharSequence, CharSequence],
    +    Array[Byte]) = {
    +    val bodyLength = in.readInt()
    +    val bodyBuff = new Array[Byte](bodyLength)
    +    in.read(bodyBuff)
    --- End diff --
    
    readFully


---
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 infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] spark pull request: SPARK-1729. Make Flume pull data from source, ...

Posted by tdas <gi...@git.apache.org>.
Github user tdas commented on a diff in the pull request:

    https://github.com/apache/spark/pull/807#discussion_r13833989
  
    --- Diff: external/flume-sink/src/main/scala/org/apache/spark/flume/sink/SparkSink.scala ---
    @@ -0,0 +1,432 @@
    +/*
    + * 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.flume.sink
    +
    +import java.net.InetSocketAddress
    +import java.nio.ByteBuffer
    +import java.util
    +import java.util.concurrent._
    +import java.util.concurrent.atomic.AtomicLong
    +
    +import scala.util.control.Breaks
    +
    +import com.google.common.util.concurrent.ThreadFactoryBuilder
    +import org.apache.avro.ipc.NettyServer
    +import org.apache.avro.ipc.specific.SpecificResponder
    +import org.apache.commons.lang.RandomStringUtils
    +import org.apache.flume.Sink.Status
    +import org.apache.flume.conf.{ConfigurationException, Configurable}
    +import org.apache.flume.sink.AbstractSink
    +import org.apache.flume.{Channel, Transaction, FlumeException, Context}
    +import org.slf4j.LoggerFactory
    +
    +import org.apache.spark.flume.{SparkSinkEvent, EventBatch, SparkFlumeProtocol}
    +
    +/**
    + * A sink that uses Avro RPC to run a server that can be polled by Spark's
    + * FlumePollingInputDStream. This sink has the following configuration parameters:
    + *
    + * hostname - The hostname to bind to. Default: 0.0.0.0
    + * port - The port to bind to. (No default - mandatory)
    + * timeout - Time in seconds after which a transaction is rolled back,
    + * if an ACK is not received from Spark within that time
    + * threads - Number of threads to use to receive requests from Spark (Default: 10)
    + *
    + */
    +// Flume forces transactions to be thread-local. So each transaction *must* be committed, or
    +// rolled back from the thread it was originally created in. So each getEvents call from Spark
    +// creates a TransactionProcessor which runs in a new thread, in which the transaction is created
    +// and events are pulled off the channel. Once the events are sent to spark,
    +// that thread is blocked and the TransactionProcessor is saved in a map,
    +// until an ACK or NACK comes back or the transaction times out (after the specified timeout).
    +// When the response comes, the TransactionProcessor is retrieved and then unblocked,
    +// at which point the transaction is committed or rolled back.
    +class SparkSink extends AbstractSink with Configurable {
    +
    +  // Size of the pool to use for holding transaction processors.
    +  private var poolSize: Integer = SparkSinkConfig.DEFAULT_THREADS
    +
    +  // Timeout for each transaction. If spark does not respond in this much time,
    +  // rollback the transaction
    +  private var transactionTimeout = SparkSinkConfig.DEFAULT_TRANSACTION_TIMEOUT
    +
    +  // Address info to bind on
    +  private var hostname: String = SparkSinkConfig.DEFAULT_HOSTNAME
    +  private var port: Int = 0
    +
    +  // Handle to the server
    +  private var serverOpt: Option[NettyServer] = None
    +
    +  // The handler that handles the callback from Avro
    +  private var handler: Option[SparkAvroCallbackHandler] = None
    +
    +  // Latch that blocks off the Flume framework from wasting 1 thread.
    +  private val blockingLatch = new CountDownLatch(1)
    +
    +  override def start() {
    +    handler = Option(new SparkAvroCallbackHandler(poolSize, getChannel, transactionTimeout))
    +    val responder = new SpecificResponder(classOf[SparkFlumeProtocol], handler.get)
    +    // Using the constructor that takes specific thread-pools requires bringing in netty
    +    // dependencies which are being excluded in the build. In practice,
    +    // Netty dependencies are already available on the JVM as Flume would have pulled them in.
    +    serverOpt = Option(new NettyServer(responder, new InetSocketAddress(hostname, port)))
    +    serverOpt.map(server => {
    +      server.start()
    +    })
    +    super.start()
    +  }
    +
    +  override def stop() {
    +    handler.map(callbackHandler => {
    +      callbackHandler.shutdown()
    +    })
    +    serverOpt.map(server => {
    +      server.close()
    +      server.join()
    +    })
    +    blockingLatch.countDown()
    +    super.stop()
    +  }
    +
    +  /**
    +   * @param ctx
    +   */
    +  override def configure(ctx: Context) {
    +    import SparkSinkConfig._
    +    hostname = ctx.getString(CONF_HOSTNAME, DEFAULT_HOSTNAME)
    +    port = Option(ctx.getInteger(CONF_PORT)).
    +      getOrElse(throw new ConfigurationException("The port to bind to must be specified"))
    +    poolSize = ctx.getInteger(THREADS, DEFAULT_THREADS)
    +    transactionTimeout = ctx.getInteger(CONF_TRANSACTION_TIMEOUT, DEFAULT_TRANSACTION_TIMEOUT)
    +  }
    +
    +  override def process(): Status = {
    +    // This method is called in a loop by the Flume framework - block it until the sink is
    +    // stopped to save CPU resources. The sink runner will interrupt this thread when the sink is
    +    // being shut down.
    +    blockingLatch.await()
    +    Status.BACKOFF
    +  }
    +}
    +
    +/**
    + * Class that implements the SparkFlumeProtocol, that is used by the Avro Netty Server to process
    + * requests. Each getEvents, ack and nack call is forwarded to an instance of this class.
    + * @param threads Number of threads to use to process requests.
    + * @param channel The channel that the sink pulls events from
    + * @param transactionTimeout Timeout in millis after which the transaction if not acked by Spark
    + *                           is rolled back.
    + */
    +private class SparkAvroCallbackHandler(val threads: Int, val channel: Channel,
    +  val transactionTimeout: Int) extends SparkFlumeProtocol {
    +  private val LOG = LoggerFactory.getLogger(classOf[SparkAvroCallbackHandler])
    +  val transactionExecutorOpt = Option(Executors.newFixedThreadPool(threads,
    +    new ThreadFactoryBuilder().setDaemon(true)
    +      .setNameFormat("Spark Sink Processor Thread - %d").build()))
    +  private val processorMap = new ConcurrentHashMap[CharSequence, TransactionProcessor]()
    +  // This sink will not persist sequence numbers and reuses them if it gets restarted.
    +  // So it is possible to commit a transaction which may have been meant for the sink before the
    +  // restart.
    +  // Since the new txn may not have the same sequence number we must guard against accidentally
    +  // committing a new transaction. To reduce the probability of that happening a random string is
    +  // prepended to the sequence number. Does not change for life of sink
    +  private val seqBase = RandomStringUtils.randomAlphanumeric(8)
    +  private val seqCounter = new AtomicLong(0)
    +
    +  /**
    +   * Returns a bunch of events to Spark over Avro RPC.
    +   * @param n Maximum number of events to return in a batch
    +   * @return [[EventBatch]] instance that has a sequence number and an array of at most n events
    +   */
    +  override def getEventBatch(n: Int): EventBatch = {
    +    val sequenceNumber = seqBase + seqCounter.incrementAndGet()
    +    val processor = new TransactionProcessor(channel, sequenceNumber,
    +      n, transactionTimeout, this)
    +    transactionExecutorOpt.map(executor => {
    +      executor.submit(processor)
    +    })
    +    // Wait until a batch is available - can be null if some error was thrown
    +    processor.getEventBatch match {
    +      case ErrorEventBatch => throw new FlumeException("Something went wrong. No events" +
    +        " retrieved from channel.")
    +      case eventBatch: EventBatch =>
    +        processorMap.put(sequenceNumber, processor)
    +        if (LOG.isDebugEnabled()) {
    +          LOG.debug("Sent " + eventBatch.getEvents.size() +
    +            " events with sequence number: " + eventBatch.getSequenceNumber)
    +        }
    +        eventBatch
    +    }
    +  }
    +
    +  /**
    +   * Called by Spark to indicate successful commit of a batch
    +   * @param sequenceNumber The sequence number of the event batch that was successful
    +   */
    +  override def ack(sequenceNumber: CharSequence): Void = {
    +    completeTransaction(sequenceNumber, success = true)
    +    null
    +  }
    +
    +  /**
    +   * Called by Spark to indicate failed commit of a batch
    +   * @param sequenceNumber The sequence number of the event batch that failed
    +   * @return
    +   */
    +  override def nack(sequenceNumber: CharSequence): Void = {
    +    completeTransaction(sequenceNumber, success = false)
    +    LOG.info("Spark failed to commit transaction. Will reattempt events.")
    +    null
    +  }
    +
    +  /**
    +   * Helper method to commit or rollback a transaction.
    +   * @param sequenceNumber The sequence number of the batch that was completed
    +   * @param success Whether the batch was successful or not.
    +   */
    +  private def completeTransaction(sequenceNumber: CharSequence, success: Boolean) {
    +    Option(removeAndGetProcessor(sequenceNumber)).map(processor => {
    +      processor.batchProcessed(success)
    +    })
    +  }
    +
    +  /**
    +   * Helper method to remove the TxnProcessor for a Sequence Number. Can be used to avoid a leak.
    +   * @param sequenceNumber
    +   * @return The transaction processor for the corresponding batch. Note that this instance is no
    +   *         longer tracked and the caller is responsible for that txn processor.
    +   */
    +  private[flume] def removeAndGetProcessor(sequenceNumber: CharSequence): TransactionProcessor = {
    +    processorMap.remove(sequenceNumber.toString) // The toString is required!
    +  }
    +
    +  /**
    +   * Shuts down the executor used to process transactions.
    +   */
    +  def shutdown() {
    +    transactionExecutorOpt.map(executor => {
    +      executor.shutdownNow()
    +    })
    +  }
    +}
    +
    +/**
    + * Object representing an empty batch returned by the txn processor due to some error.
    + */
    +case object ErrorEventBatch extends EventBatch
    +
    +// Flume forces transactions to be thread-local (horrible, I know!)
    +// So the sink basically spawns a new thread to pull the events out within a transaction.
    +// The thread fills in the event batch object that is set before the thread is scheduled.
    +// After filling it in, the thread waits on a condition - which is released only
    +// when the success message comes back for the specific sequence number for that event batch.
    +/**
    + * This class represents a transaction on the Flume channel. This class runs a separate thread
    + * which owns the transaction. The thread is blocked until the success call for that transaction
    + * comes back with an ACK or NACK.
    + * @param channel The channel from which to pull events
    + * @param seqNum The sequence number to use for the transaction. Must be unique
    + * @param maxBatchSize The maximum number of events to process per batch
    + * @param transactionTimeout Time in seconds after which a transaction must be rolled back
    + *                           without waiting for an ACK from Spark
    + * @param parent The parent [[SparkAvroCallbackHandler]] instance, for reporting timeouts
    + */
    +private class TransactionProcessor(val channel: Channel, val seqNum: String,
    +  var maxBatchSize: Int, val transactionTimeout: Int,
    +  val parent: SparkAvroCallbackHandler) extends Callable[Void] {
    +
    +  private val LOG = LoggerFactory.getLogger(classOf[TransactionProcessor])
    +
    +  // If a real batch is not returned, we always have to return an error batch.
    +  @volatile private var eventBatch: EventBatch = ErrorEventBatch
    +
    +  // Synchronization primitives
    +  val batchGeneratedLatch = new CountDownLatch(1)
    +  val batchAckLatch = new CountDownLatch(1)
    +
    +  // Sanity check to ensure we don't loop like crazy
    +  val totalAttemptsToRemoveFromChannel = Int.MaxValue / 2
    +
    +  // OK to use volatile, since the change would only make this true (otherwise it will be
    +  // changed to false - we never apply a negation operation to this) - which means the transaction
    +  // succeeded.
    +  @volatile private var batchSuccess = false
    +
    +  // The transaction that this processor would handle
    +  var txOpt: Option[Transaction] = None
    +
    +  /**
    +   * Get an event batch from the channel. This method will block until a batch of events is
    +   * available from the channel. If no events are available after a large number of attempts of
    +   * polling the channel, this method will return [[ErrorEventBatch]].
    +   *
    +   * @return An [[EventBatch]] instance with sequence number set to [[seqNum]], filled with a
    +   *         maximum of [[maxBatchSize]] events
    +   */
    +  def getEventBatch: EventBatch = {
    +    batchGeneratedLatch.await()
    +    eventBatch
    +  }
    +
    +  /**
    +   * This method is to be called by the sink when it receives an ACK or NACK from Spark. This
    +   * method is a no-op if it is called after [[transactionTimeout]] has expired since
    +   * [[getEventBatch]] returned a batch of events.
    +   * @param success True if an ACK was received and the transaction should be committed, else false.
    +   */
    +  def batchProcessed(success: Boolean) {
    +    if (LOG.isDebugEnabled) {
    +      LOG.debug("Batch processed for sequence number: " + seqNum)
    +    }
    +    batchSuccess = success
    +    batchAckLatch.countDown()
    +  }
    +
    +  /**
    +   * Populates events into the event batch. If the batch cannot be populated,
    +   * this method will not set the event batch which will stay [[ErrorEventBatch]]
    +   */
    +  private def populateEvents() {
    +    try {
    +      txOpt = Option(channel.getTransaction)
    +      txOpt.map(tx => {
    +        tx.begin()
    +        val events = new util.ArrayList[SparkSinkEvent](maxBatchSize)
    +        val loop = new Breaks
    +        var gotEventsInThisTxn = false
    +        var loopCounter: Int = 0
    +        loop.breakable {
    +          while (events.size() < maxBatchSize
    +            && loopCounter < totalAttemptsToRemoveFromChannel) {
    +            loopCounter += 1
    +            Option(channel.take()) match {
    +              case Some(event) =>
    +                events.add(new SparkSinkEvent(toCharSequenceMap(event.getHeaders),
    +                  ByteBuffer.wrap(event.getBody)))
    +                gotEventsInThisTxn = true
    +              case None =>
    +                if (!gotEventsInThisTxn) {
    +                  TimeUnit.MILLISECONDS.sleep(500)
    +                } else {
    +                  loop.break()
    +                }
    +            }
    +          }
    +        }
    +        if (!gotEventsInThisTxn) {
    +          throw new FlumeException("Tried too many times, didn't get any events from the channel")
    +        }
    +        // At this point, the events are available, so fill them into the event batch
    +        eventBatch = new EventBatch(seqNum, events)
    +      })
    +    } catch {
    +      case e: Throwable =>
    +        LOG.error("Error while processing transaction.", e)
    +        try {
    +          txOpt.map(tx => {
    +            rollbackAndClose(tx, close = true)
    +          })
    +        } finally {
    +          // Avro might serialize the exception and cause a NACK,
    +          // so don't bother with the transaction
    +          txOpt = None
    +        }
    +    } finally {
    +      batchGeneratedLatch.countDown()
    +    }
    +  }
    +
    +  /**
    +   * Waits for upto [[transactionTimeout]] seconds for an ACK. If an ACK comes in,
    +   * this method commits the transaction with the channel. If the ACK does not come in within
    +   * that time or a NACK comes in, this method rolls back the transaction.
    +   */
    +  private def processAckOrNack() {
    +    batchAckLatch.await(transactionTimeout, TimeUnit.SECONDS)
    +    txOpt.map(tx => {
    +      if (batchSuccess) {
    +        try {
    +          tx.commit()
    +        } catch {
    +          case e: Throwable =>
    +            rollbackAndClose(tx, close = false) // tx will be closed later anyway
    +        } finally {
    +          tx.close()
    --- End diff --
    
    NVM, I didnt see the close=false. However, is it actually a problem to call close twice? As in, often close() are idempotent and can be called multiple times.


---
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 infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] spark pull request: SPARK-1729. Make Flume pull data from source, ...

Posted by tdas <gi...@git.apache.org>.
Github user tdas commented on a diff in the pull request:

    https://github.com/apache/spark/pull/807#discussion_r13835043
  
    --- Diff: external/flume-sink/src/main/scala/org/apache/spark/flume/sink/SparkSink.scala ---
    @@ -0,0 +1,432 @@
    +/*
    + * 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.flume.sink
    +
    +import java.net.InetSocketAddress
    +import java.nio.ByteBuffer
    +import java.util
    +import java.util.concurrent._
    +import java.util.concurrent.atomic.AtomicLong
    +
    +import scala.util.control.Breaks
    +
    +import com.google.common.util.concurrent.ThreadFactoryBuilder
    +import org.apache.avro.ipc.NettyServer
    +import org.apache.avro.ipc.specific.SpecificResponder
    +import org.apache.commons.lang.RandomStringUtils
    +import org.apache.flume.Sink.Status
    +import org.apache.flume.conf.{ConfigurationException, Configurable}
    +import org.apache.flume.sink.AbstractSink
    +import org.apache.flume.{Channel, Transaction, FlumeException, Context}
    +import org.slf4j.LoggerFactory
    +
    +import org.apache.spark.flume.{SparkSinkEvent, EventBatch, SparkFlumeProtocol}
    +
    +/**
    + * A sink that uses Avro RPC to run a server that can be polled by Spark's
    + * FlumePollingInputDStream. This sink has the following configuration parameters:
    + *
    + * hostname - The hostname to bind to. Default: 0.0.0.0
    + * port - The port to bind to. (No default - mandatory)
    + * timeout - Time in seconds after which a transaction is rolled back,
    + * if an ACK is not received from Spark within that time
    + * threads - Number of threads to use to receive requests from Spark (Default: 10)
    + *
    + */
    +// Flume forces transactions to be thread-local. So each transaction *must* be committed, or
    +// rolled back from the thread it was originally created in. So each getEvents call from Spark
    +// creates a TransactionProcessor which runs in a new thread, in which the transaction is created
    +// and events are pulled off the channel. Once the events are sent to spark,
    +// that thread is blocked and the TransactionProcessor is saved in a map,
    +// until an ACK or NACK comes back or the transaction times out (after the specified timeout).
    +// When the response comes, the TransactionProcessor is retrieved and then unblocked,
    +// at which point the transaction is committed or rolled back.
    +class SparkSink extends AbstractSink with Configurable {
    +
    +  // Size of the pool to use for holding transaction processors.
    +  private var poolSize: Integer = SparkSinkConfig.DEFAULT_THREADS
    +
    +  // Timeout for each transaction. If spark does not respond in this much time,
    +  // rollback the transaction
    +  private var transactionTimeout = SparkSinkConfig.DEFAULT_TRANSACTION_TIMEOUT
    +
    +  // Address info to bind on
    +  private var hostname: String = SparkSinkConfig.DEFAULT_HOSTNAME
    +  private var port: Int = 0
    +
    +  // Handle to the server
    +  private var serverOpt: Option[NettyServer] = None
    +
    +  // The handler that handles the callback from Avro
    +  private var handler: Option[SparkAvroCallbackHandler] = None
    +
    +  // Latch that blocks off the Flume framework from wasting 1 thread.
    +  private val blockingLatch = new CountDownLatch(1)
    +
    +  override def start() {
    +    handler = Option(new SparkAvroCallbackHandler(poolSize, getChannel, transactionTimeout))
    +    val responder = new SpecificResponder(classOf[SparkFlumeProtocol], handler.get)
    +    // Using the constructor that takes specific thread-pools requires bringing in netty
    +    // dependencies which are being excluded in the build. In practice,
    +    // Netty dependencies are already available on the JVM as Flume would have pulled them in.
    +    serverOpt = Option(new NettyServer(responder, new InetSocketAddress(hostname, port)))
    +    serverOpt.map(server => {
    +      server.start()
    +    })
    +    super.start()
    +  }
    +
    +  override def stop() {
    +    handler.map(callbackHandler => {
    +      callbackHandler.shutdown()
    +    })
    +    serverOpt.map(server => {
    +      server.close()
    +      server.join()
    +    })
    +    blockingLatch.countDown()
    +    super.stop()
    +  }
    +
    +  /**
    +   * @param ctx
    --- End diff --
    
    this  doc is not really useful


---
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 infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] spark pull request: SPARK-1729. Make Flume pull data from source, ...

Posted by tdas <gi...@git.apache.org>.
Github user tdas commented on a diff in the pull request:

    https://github.com/apache/spark/pull/807#discussion_r13834698
  
    --- Diff: external/flume-sink/src/main/scala/org/apache/spark/flume/sink/SparkSink.scala ---
    @@ -0,0 +1,432 @@
    +/*
    + * 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.flume.sink
    +
    +import java.net.InetSocketAddress
    +import java.nio.ByteBuffer
    +import java.util
    +import java.util.concurrent._
    +import java.util.concurrent.atomic.AtomicLong
    +
    +import scala.util.control.Breaks
    +
    +import com.google.common.util.concurrent.ThreadFactoryBuilder
    +import org.apache.avro.ipc.NettyServer
    +import org.apache.avro.ipc.specific.SpecificResponder
    +import org.apache.commons.lang.RandomStringUtils
    +import org.apache.flume.Sink.Status
    +import org.apache.flume.conf.{ConfigurationException, Configurable}
    +import org.apache.flume.sink.AbstractSink
    +import org.apache.flume.{Channel, Transaction, FlumeException, Context}
    +import org.slf4j.LoggerFactory
    +
    +import org.apache.spark.flume.{SparkSinkEvent, EventBatch, SparkFlumeProtocol}
    +
    +/**
    + * A sink that uses Avro RPC to run a server that can be polled by Spark's
    + * FlumePollingInputDStream. This sink has the following configuration parameters:
    + *
    + * hostname - The hostname to bind to. Default: 0.0.0.0
    + * port - The port to bind to. (No default - mandatory)
    + * timeout - Time in seconds after which a transaction is rolled back,
    + * if an ACK is not received from Spark within that time
    + * threads - Number of threads to use to receive requests from Spark (Default: 10)
    + *
    + */
    +// Flume forces transactions to be thread-local. So each transaction *must* be committed, or
    +// rolled back from the thread it was originally created in. So each getEvents call from Spark
    +// creates a TransactionProcessor which runs in a new thread, in which the transaction is created
    +// and events are pulled off the channel. Once the events are sent to spark,
    +// that thread is blocked and the TransactionProcessor is saved in a map,
    +// until an ACK or NACK comes back or the transaction times out (after the specified timeout).
    +// When the response comes, the TransactionProcessor is retrieved and then unblocked,
    +// at which point the transaction is committed or rolled back.
    +class SparkSink extends AbstractSink with Configurable {
    +
    +  // Size of the pool to use for holding transaction processors.
    +  private var poolSize: Integer = SparkSinkConfig.DEFAULT_THREADS
    +
    +  // Timeout for each transaction. If spark does not respond in this much time,
    +  // rollback the transaction
    +  private var transactionTimeout = SparkSinkConfig.DEFAULT_TRANSACTION_TIMEOUT
    +
    +  // Address info to bind on
    +  private var hostname: String = SparkSinkConfig.DEFAULT_HOSTNAME
    +  private var port: Int = 0
    +
    +  // Handle to the server
    +  private var serverOpt: Option[NettyServer] = None
    +
    +  // The handler that handles the callback from Avro
    +  private var handler: Option[SparkAvroCallbackHandler] = None
    +
    +  // Latch that blocks off the Flume framework from wasting 1 thread.
    +  private val blockingLatch = new CountDownLatch(1)
    +
    +  override def start() {
    +    handler = Option(new SparkAvroCallbackHandler(poolSize, getChannel, transactionTimeout))
    +    val responder = new SpecificResponder(classOf[SparkFlumeProtocol], handler.get)
    +    // Using the constructor that takes specific thread-pools requires bringing in netty
    +    // dependencies which are being excluded in the build. In practice,
    +    // Netty dependencies are already available on the JVM as Flume would have pulled them in.
    +    serverOpt = Option(new NettyServer(responder, new InetSocketAddress(hostname, port)))
    +    serverOpt.map(server => {
    +      server.start()
    +    })
    +    super.start()
    +  }
    +
    +  override def stop() {
    +    handler.map(callbackHandler => {
    +      callbackHandler.shutdown()
    +    })
    +    serverOpt.map(server => {
    +      server.close()
    +      server.join()
    +    })
    +    blockingLatch.countDown()
    +    super.stop()
    +  }
    +
    +  /**
    +   * @param ctx
    +   */
    +  override def configure(ctx: Context) {
    +    import SparkSinkConfig._
    +    hostname = ctx.getString(CONF_HOSTNAME, DEFAULT_HOSTNAME)
    +    port = Option(ctx.getInteger(CONF_PORT)).
    +      getOrElse(throw new ConfigurationException("The port to bind to must be specified"))
    +    poolSize = ctx.getInteger(THREADS, DEFAULT_THREADS)
    +    transactionTimeout = ctx.getInteger(CONF_TRANSACTION_TIMEOUT, DEFAULT_TRANSACTION_TIMEOUT)
    +  }
    +
    +  override def process(): Status = {
    +    // This method is called in a loop by the Flume framework - block it until the sink is
    +    // stopped to save CPU resources. The sink runner will interrupt this thread when the sink is
    +    // being shut down.
    +    blockingLatch.await()
    +    Status.BACKOFF
    +  }
    +}
    +
    +/**
    + * Class that implements the SparkFlumeProtocol, that is used by the Avro Netty Server to process
    + * requests. Each getEvents, ack and nack call is forwarded to an instance of this class.
    + * @param threads Number of threads to use to process requests.
    + * @param channel The channel that the sink pulls events from
    + * @param transactionTimeout Timeout in millis after which the transaction if not acked by Spark
    + *                           is rolled back.
    + */
    +private class SparkAvroCallbackHandler(val threads: Int, val channel: Channel,
    +  val transactionTimeout: Int) extends SparkFlumeProtocol {
    +  private val LOG = LoggerFactory.getLogger(classOf[SparkAvroCallbackHandler])
    +  val transactionExecutorOpt = Option(Executors.newFixedThreadPool(threads,
    +    new ThreadFactoryBuilder().setDaemon(true)
    +      .setNameFormat("Spark Sink Processor Thread - %d").build()))
    +  private val processorMap = new ConcurrentHashMap[CharSequence, TransactionProcessor]()
    +  // This sink will not persist sequence numbers and reuses them if it gets restarted.
    +  // So it is possible to commit a transaction which may have been meant for the sink before the
    +  // restart.
    +  // Since the new txn may not have the same sequence number we must guard against accidentally
    +  // committing a new transaction. To reduce the probability of that happening a random string is
    +  // prepended to the sequence number. Does not change for life of sink
    +  private val seqBase = RandomStringUtils.randomAlphanumeric(8)
    +  private val seqCounter = new AtomicLong(0)
    +
    +  /**
    +   * Returns a bunch of events to Spark over Avro RPC.
    +   * @param n Maximum number of events to return in a batch
    +   * @return [[EventBatch]] instance that has a sequence number and an array of at most n events
    +   */
    +  override def getEventBatch(n: Int): EventBatch = {
    +    val sequenceNumber = seqBase + seqCounter.incrementAndGet()
    +    val processor = new TransactionProcessor(channel, sequenceNumber,
    +      n, transactionTimeout, this)
    +    transactionExecutorOpt.map(executor => {
    +      executor.submit(processor)
    +    })
    +    // Wait until a batch is available - can be null if some error was thrown
    +    processor.getEventBatch match {
    +      case ErrorEventBatch => throw new FlumeException("Something went wrong. No events" +
    +        " retrieved from channel.")
    +      case eventBatch: EventBatch =>
    +        processorMap.put(sequenceNumber, processor)
    +        if (LOG.isDebugEnabled()) {
    +          LOG.debug("Sent " + eventBatch.getEvents.size() +
    +            " events with sequence number: " + eventBatch.getSequenceNumber)
    +        }
    +        eventBatch
    +    }
    +  }
    +
    +  /**
    +   * Called by Spark to indicate successful commit of a batch
    +   * @param sequenceNumber The sequence number of the event batch that was successful
    +   */
    +  override def ack(sequenceNumber: CharSequence): Void = {
    +    completeTransaction(sequenceNumber, success = true)
    +    null
    +  }
    +
    +  /**
    +   * Called by Spark to indicate failed commit of a batch
    +   * @param sequenceNumber The sequence number of the event batch that failed
    +   * @return
    +   */
    +  override def nack(sequenceNumber: CharSequence): Void = {
    +    completeTransaction(sequenceNumber, success = false)
    +    LOG.info("Spark failed to commit transaction. Will reattempt events.")
    +    null
    +  }
    +
    +  /**
    +   * Helper method to commit or rollback a transaction.
    +   * @param sequenceNumber The sequence number of the batch that was completed
    +   * @param success Whether the batch was successful or not.
    +   */
    +  private def completeTransaction(sequenceNumber: CharSequence, success: Boolean) {
    +    Option(removeAndGetProcessor(sequenceNumber)).map(processor => {
    +      processor.batchProcessed(success)
    +    })
    +  }
    +
    +  /**
    +   * Helper method to remove the TxnProcessor for a Sequence Number. Can be used to avoid a leak.
    +   * @param sequenceNumber
    +   * @return The transaction processor for the corresponding batch. Note that this instance is no
    +   *         longer tracked and the caller is responsible for that txn processor.
    +   */
    +  private[flume] def removeAndGetProcessor(sequenceNumber: CharSequence): TransactionProcessor = {
    +    processorMap.remove(sequenceNumber.toString) // The toString is required!
    +  }
    +
    +  /**
    +   * Shuts down the executor used to process transactions.
    +   */
    +  def shutdown() {
    +    transactionExecutorOpt.map(executor => {
    +      executor.shutdownNow()
    +    })
    +  }
    +}
    +
    +/**
    + * Object representing an empty batch returned by the txn processor due to some error.
    + */
    +case object ErrorEventBatch extends EventBatch
    +
    +// Flume forces transactions to be thread-local (horrible, I know!)
    +// So the sink basically spawns a new thread to pull the events out within a transaction.
    +// The thread fills in the event batch object that is set before the thread is scheduled.
    +// After filling it in, the thread waits on a condition - which is released only
    +// when the success message comes back for the specific sequence number for that event batch.
    +/**
    + * This class represents a transaction on the Flume channel. This class runs a separate thread
    + * which owns the transaction. The thread is blocked until the success call for that transaction
    + * comes back with an ACK or NACK.
    + * @param channel The channel from which to pull events
    + * @param seqNum The sequence number to use for the transaction. Must be unique
    + * @param maxBatchSize The maximum number of events to process per batch
    + * @param transactionTimeout Time in seconds after which a transaction must be rolled back
    + *                           without waiting for an ACK from Spark
    + * @param parent The parent [[SparkAvroCallbackHandler]] instance, for reporting timeouts
    + */
    +private class TransactionProcessor(val channel: Channel, val seqNum: String,
    +  var maxBatchSize: Int, val transactionTimeout: Int,
    +  val parent: SparkAvroCallbackHandler) extends Callable[Void] {
    +
    +  private val LOG = LoggerFactory.getLogger(classOf[TransactionProcessor])
    +
    +  // If a real batch is not returned, we always have to return an error batch.
    +  @volatile private var eventBatch: EventBatch = ErrorEventBatch
    +
    +  // Synchronization primitives
    +  val batchGeneratedLatch = new CountDownLatch(1)
    +  val batchAckLatch = new CountDownLatch(1)
    +
    +  // Sanity check to ensure we don't loop like crazy
    +  val totalAttemptsToRemoveFromChannel = Int.MaxValue / 2
    +
    +  // OK to use volatile, since the change would only make this true (otherwise it will be
    +  // changed to false - we never apply a negation operation to this) - which means the transaction
    +  // succeeded.
    +  @volatile private var batchSuccess = false
    +
    +  // The transaction that this processor would handle
    +  var txOpt: Option[Transaction] = None
    +
    +  /**
    +   * Get an event batch from the channel. This method will block until a batch of events is
    +   * available from the channel. If no events are available after a large number of attempts of
    +   * polling the channel, this method will return [[ErrorEventBatch]].
    +   *
    +   * @return An [[EventBatch]] instance with sequence number set to [[seqNum]], filled with a
    +   *         maximum of [[maxBatchSize]] events
    +   */
    +  def getEventBatch: EventBatch = {
    +    batchGeneratedLatch.await()
    +    eventBatch
    +  }
    +
    +  /**
    +   * This method is to be called by the sink when it receives an ACK or NACK from Spark. This
    +   * method is a no-op if it is called after [[transactionTimeout]] has expired since
    +   * [[getEventBatch]] returned a batch of events.
    +   * @param success True if an ACK was received and the transaction should be committed, else false.
    +   */
    +  def batchProcessed(success: Boolean) {
    +    if (LOG.isDebugEnabled) {
    +      LOG.debug("Batch processed for sequence number: " + seqNum)
    +    }
    +    batchSuccess = success
    +    batchAckLatch.countDown()
    +  }
    +
    +  /**
    +   * Populates events into the event batch. If the batch cannot be populated,
    +   * this method will not set the event batch which will stay [[ErrorEventBatch]]
    +   */
    +  private def populateEvents() {
    +    try {
    +      txOpt = Option(channel.getTransaction)
    +      txOpt.map(tx => {
    +        tx.begin()
    +        val events = new util.ArrayList[SparkSinkEvent](maxBatchSize)
    +        val loop = new Breaks
    +        var gotEventsInThisTxn = false
    +        var loopCounter: Int = 0
    +        loop.breakable {
    +          while (events.size() < maxBatchSize
    +            && loopCounter < totalAttemptsToRemoveFromChannel) {
    +            loopCounter += 1
    +            Option(channel.take()) match {
    +              case Some(event) =>
    +                events.add(new SparkSinkEvent(toCharSequenceMap(event.getHeaders),
    +                  ByteBuffer.wrap(event.getBody)))
    +                gotEventsInThisTxn = true
    +              case None =>
    +                if (!gotEventsInThisTxn) {
    +                  TimeUnit.MILLISECONDS.sleep(500)
    --- End diff --
    
    This 500 milliseconds seems arbitrary. This should be parameterized as i think this should correlate with spark streaming's minibatch times which is 200 ms by default.


---
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 infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] spark pull request: SPARK-1729. Make Flume pull data from source, ...

Posted by srowen <gi...@git.apache.org>.
Github user srowen commented on a diff in the pull request:

    https://github.com/apache/spark/pull/807#discussion_r12781197
  
    --- Diff: external/flume-sink/pom.xml ---
    @@ -0,0 +1,82 @@
    +<?xml version="1.0" encoding="UTF-8"?>
    --- End diff --
    
    Pardon for jumping in with comments, but why a new module instead of external/flume?


---
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 infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] spark pull request: SPARK-1729. Make Flume pull data from source, ...

Posted by harishreedharan <gi...@git.apache.org>.
Github user harishreedharan commented on a diff in the pull request:

    https://github.com/apache/spark/pull/807#discussion_r13835462
  
    --- Diff: external/flume-sink/src/main/scala/org/apache/spark/flume/sink/SparkSink.scala ---
    @@ -0,0 +1,432 @@
    +/*
    + * 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.flume.sink
    +
    +import java.net.InetSocketAddress
    +import java.nio.ByteBuffer
    +import java.util
    +import java.util.concurrent._
    +import java.util.concurrent.atomic.AtomicLong
    +
    +import scala.util.control.Breaks
    +
    +import com.google.common.util.concurrent.ThreadFactoryBuilder
    +import org.apache.avro.ipc.NettyServer
    +import org.apache.avro.ipc.specific.SpecificResponder
    +import org.apache.commons.lang.RandomStringUtils
    +import org.apache.flume.Sink.Status
    +import org.apache.flume.conf.{ConfigurationException, Configurable}
    +import org.apache.flume.sink.AbstractSink
    +import org.apache.flume.{Channel, Transaction, FlumeException, Context}
    +import org.slf4j.LoggerFactory
    +
    +import org.apache.spark.flume.{SparkSinkEvent, EventBatch, SparkFlumeProtocol}
    +
    +/**
    + * A sink that uses Avro RPC to run a server that can be polled by Spark's
    + * FlumePollingInputDStream. This sink has the following configuration parameters:
    + *
    + * hostname - The hostname to bind to. Default: 0.0.0.0
    + * port - The port to bind to. (No default - mandatory)
    + * timeout - Time in seconds after which a transaction is rolled back,
    + * if an ACK is not received from Spark within that time
    + * threads - Number of threads to use to receive requests from Spark (Default: 10)
    + *
    + */
    +// Flume forces transactions to be thread-local. So each transaction *must* be committed, or
    +// rolled back from the thread it was originally created in. So each getEvents call from Spark
    +// creates a TransactionProcessor which runs in a new thread, in which the transaction is created
    +// and events are pulled off the channel. Once the events are sent to spark,
    +// that thread is blocked and the TransactionProcessor is saved in a map,
    +// until an ACK or NACK comes back or the transaction times out (after the specified timeout).
    +// When the response comes, the TransactionProcessor is retrieved and then unblocked,
    +// at which point the transaction is committed or rolled back.
    +class SparkSink extends AbstractSink with Configurable {
    +
    +  // Size of the pool to use for holding transaction processors.
    +  private var poolSize: Integer = SparkSinkConfig.DEFAULT_THREADS
    +
    +  // Timeout for each transaction. If spark does not respond in this much time,
    +  // rollback the transaction
    +  private var transactionTimeout = SparkSinkConfig.DEFAULT_TRANSACTION_TIMEOUT
    +
    +  // Address info to bind on
    +  private var hostname: String = SparkSinkConfig.DEFAULT_HOSTNAME
    +  private var port: Int = 0
    +
    +  // Handle to the server
    +  private var serverOpt: Option[NettyServer] = None
    +
    +  // The handler that handles the callback from Avro
    +  private var handler: Option[SparkAvroCallbackHandler] = None
    +
    +  // Latch that blocks off the Flume framework from wasting 1 thread.
    +  private val blockingLatch = new CountDownLatch(1)
    +
    +  override def start() {
    +    handler = Option(new SparkAvroCallbackHandler(poolSize, getChannel, transactionTimeout))
    +    val responder = new SpecificResponder(classOf[SparkFlumeProtocol], handler.get)
    +    // Using the constructor that takes specific thread-pools requires bringing in netty
    +    // dependencies which are being excluded in the build. In practice,
    +    // Netty dependencies are already available on the JVM as Flume would have pulled them in.
    +    serverOpt = Option(new NettyServer(responder, new InetSocketAddress(hostname, port)))
    +    serverOpt.map(server => {
    +      server.start()
    +    })
    +    super.start()
    +  }
    +
    +  override def stop() {
    +    handler.map(callbackHandler => {
    +      callbackHandler.shutdown()
    +    })
    +    serverOpt.map(server => {
    +      server.close()
    +      server.join()
    +    })
    +    blockingLatch.countDown()
    +    super.stop()
    +  }
    +
    +  /**
    +   * @param ctx
    --- End diff --
    
    I will change this to inherit the doc from the original api.


---
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 infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] spark pull request: SPARK-1729. Make Flume pull data from source, ...

Posted by harishreedharan <gi...@git.apache.org>.
Github user harishreedharan commented on a diff in the pull request:

    https://github.com/apache/spark/pull/807#discussion_r13471064
  
    --- Diff: external/flume-sink/src/main/scala/org/apache/spark/flume/sink/SparkSink.scala ---
    @@ -0,0 +1,392 @@
    +/*
    + * 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.flume.sink
    +
    +import org.apache.flume.sink.AbstractSink
    +import java.util.concurrent.locks.ReentrantLock
    +import org.apache.flume.Sink.Status
    +import org.apache.spark.flume.{SparkSinkEvent, EventBatch, SparkFlumeProtocol}
    +import scala.util.control.Breaks
    +import java.nio.ByteBuffer
    +import org.apache.flume.{FlumeException, Context}
    +import org.slf4j.LoggerFactory
    +import java.util.concurrent.atomic.AtomicLong
    +import org.apache.commons.lang.RandomStringUtils
    +import java.util.concurrent._
    +import java.util
    +import org.apache.flume.conf.{ConfigurationException, Configurable}
    +import com.google.common.util.concurrent.ThreadFactoryBuilder
    +import org.apache.avro.ipc.NettyServer
    +import org.apache.avro.ipc.specific.SpecificResponder
    +import java.net.InetSocketAddress
    +
    +class SparkSink() extends AbstractSink with Configurable {
    +  private val LOG = LoggerFactory.getLogger(this.getClass)
    +  private val lock = new ReentrantLock()
    +  private val blockingCondition = lock.newCondition()
    --- End diff --
    
    Actually this will likely be accessed by several threads (since Netty uses a threadpool and will uses several threads to process incoming connections) - in which case, locks are likely to perform better.


---
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 infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] spark pull request: SPARK-1729. Make Flume pull data from source, ...

Posted by harishreedharan <gi...@git.apache.org>.
Github user harishreedharan commented on a diff in the pull request:

    https://github.com/apache/spark/pull/807#discussion_r13466499
  
    --- Diff: external/flume/src/main/scala/org/apache/spark/streaming/flume/FlumePollingInputDStream.scala ---
    @@ -0,0 +1,165 @@
    +/*
    + * 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.streaming.flume
    +
    +
    +import java.io.{ObjectOutput, ObjectInput, Externalizable}
    +import java.net.InetSocketAddress
    +import java.nio.ByteBuffer
    +import java.util.concurrent.{TimeUnit, Executors}
    +
    +import scala.collection.JavaConversions._
    +import scala.collection.mutable
    +import scala.reflect.ClassTag
    +
    +import com.google.common.util.concurrent.ThreadFactoryBuilder
    +import org.apache.avro.ipc.NettyTransceiver
    +import org.apache.avro.ipc.specific.SpecificRequestor
    +import org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory
    +
    +import org.apache.spark.Logging
    +import org.apache.spark.flume.{SparkSinkEvent, SparkFlumeProtocol}
    +import org.apache.spark.storage.StorageLevel
    +import org.apache.spark.streaming.StreamingContext
    +import org.apache.spark.streaming.dstream.ReceiverInputDStream
    +import org.apache.spark.streaming.receiver.Receiver
    +
    +
    +
    +class FlumePollingInputDStream[T: ClassTag](
    +  @transient ssc_ : StreamingContext,
    +  val addresses: Seq[InetSocketAddress],
    +  val maxBatchSize: Int,
    +  val parallelism: Int,
    +  storageLevel: StorageLevel
    +) extends ReceiverInputDStream[SparkPollingEvent](ssc_) {
    +  /**
    +   * Gets the receiver object that will be sent to the worker nodes
    +   * to receive data. This method needs to defined by any specific implementation
    +   * of a NetworkInputDStream.
    +   */
    +  override def getReceiver(): Receiver[SparkPollingEvent] = {
    +    new FlumePollingReceiver(addresses, maxBatchSize, parallelism, storageLevel)
    +  }
    +}
    +
    +private[streaming] class FlumePollingReceiver(
    +  addresses: Seq[InetSocketAddress],
    +  maxBatchSize: Int,
    +  parallelism: Int,
    +  storageLevel: StorageLevel
    +) extends Receiver[SparkPollingEvent](storageLevel) with Logging {
    +
    +  lazy val channelFactoryExecutor =
    +    Executors.newCachedThreadPool(new ThreadFactoryBuilder().setDaemon(true).
    +      setNameFormat("Flume Receiver Channel Thread - %d").build())
    +
    +  lazy val channelFactory =
    +    new NioClientSocketChannelFactory(channelFactoryExecutor, channelFactoryExecutor)
    +
    +  lazy val receiverExecutor = Executors.newFixedThreadPool(parallelism,
    +    new ThreadFactoryBuilder().setDaemon(true).setNameFormat("Flume Receiver Thread - %d").build())
    +
    +  private var connections = Array.empty[FlumeConnection] // temporarily empty, filled in later
    +
    +  override def onStart(): Unit = {
    +    val connectionBuilder = new mutable.ArrayBuilder.ofRef[FlumeConnection]()
    +    addresses.map(host => {
    +      val transceiver = new NettyTransceiver(host, channelFactory)
    +      val client = SpecificRequestor.getClient(classOf[SparkFlumeProtocol.Callback], transceiver)
    +      connectionBuilder += new FlumeConnection(transceiver, client)
    +    })
    +    connections = connectionBuilder.result()
    --- End diff --
    
    This ends up in data being copied, but since it is one-time I guess it is ok.


---
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 infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] spark pull request: SPARK-1729. Make Flume pull data from source, ...

Posted by joyyoj <gi...@git.apache.org>.
Github user joyyoj commented on a diff in the pull request:

    https://github.com/apache/spark/pull/807#discussion_r13740434
  
    --- Diff: external/flume/src/main/scala/org/apache/spark/streaming/flume/EventTransformer.scala ---
    @@ -0,0 +1,72 @@
    +/*
    + * 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.streaming.flume
    +
    +import java.io.{ObjectOutput, ObjectInput}
    +
    +import scala.collection.JavaConversions._
    +
    +import org.apache.spark.util.Utils
    +import org.apache.spark.Logging
    +
    +/**
    + * A simple object that provides the implementation of readExternal and writeExternal for both
    + * the wrapper classes for Flume-style Events.
    + */
    +object EventTransformer extends Logging {
    +  def readExternal(in: ObjectInput): (java.util.HashMap[CharSequence, CharSequence],
    +    Array[Byte]) = {
    +    val bodyLength = in.readInt()
    +    val bodyBuff = new Array[Byte](bodyLength)
    +    in.read(bodyBuff)
    +
    +    val numHeaders = in.readInt()
    +    val headers = new java.util.HashMap[CharSequence, CharSequence]
    +
    +    for (i <- 0 until numHeaders) {
    +      val keyLength = in.readInt()
    +      val keyBuff = new Array[Byte](keyLength)
    +      in.read(keyBuff)
    --- End diff --
    
    readFully


---
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 infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] spark pull request: SPARK-1729. Make Flume pull data from source, ...

Posted by harishreedharan <gi...@git.apache.org>.
Github user harishreedharan commented on a diff in the pull request:

    https://github.com/apache/spark/pull/807#discussion_r13838021
  
    --- Diff: external/flume-sink/src/main/scala/org/apache/spark/flume/sink/SparkSink.scala ---
    @@ -0,0 +1,432 @@
    +/*
    + * 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.flume.sink
    +
    +import java.net.InetSocketAddress
    +import java.nio.ByteBuffer
    +import java.util
    +import java.util.concurrent._
    +import java.util.concurrent.atomic.AtomicLong
    +
    +import scala.util.control.Breaks
    +
    +import com.google.common.util.concurrent.ThreadFactoryBuilder
    +import org.apache.avro.ipc.NettyServer
    +import org.apache.avro.ipc.specific.SpecificResponder
    +import org.apache.commons.lang.RandomStringUtils
    +import org.apache.flume.Sink.Status
    +import org.apache.flume.conf.{ConfigurationException, Configurable}
    +import org.apache.flume.sink.AbstractSink
    +import org.apache.flume.{Channel, Transaction, FlumeException, Context}
    +import org.slf4j.LoggerFactory
    +
    +import org.apache.spark.flume.{SparkSinkEvent, EventBatch, SparkFlumeProtocol}
    +
    +/**
    + * A sink that uses Avro RPC to run a server that can be polled by Spark's
    + * FlumePollingInputDStream. This sink has the following configuration parameters:
    + *
    + * hostname - The hostname to bind to. Default: 0.0.0.0
    + * port - The port to bind to. (No default - mandatory)
    + * timeout - Time in seconds after which a transaction is rolled back,
    + * if an ACK is not received from Spark within that time
    + * threads - Number of threads to use to receive requests from Spark (Default: 10)
    + *
    + */
    +// Flume forces transactions to be thread-local. So each transaction *must* be committed, or
    +// rolled back from the thread it was originally created in. So each getEvents call from Spark
    +// creates a TransactionProcessor which runs in a new thread, in which the transaction is created
    +// and events are pulled off the channel. Once the events are sent to spark,
    +// that thread is blocked and the TransactionProcessor is saved in a map,
    +// until an ACK or NACK comes back or the transaction times out (after the specified timeout).
    +// When the response comes, the TransactionProcessor is retrieved and then unblocked,
    +// at which point the transaction is committed or rolled back.
    +class SparkSink extends AbstractSink with Configurable {
    +
    +  // Size of the pool to use for holding transaction processors.
    +  private var poolSize: Integer = SparkSinkConfig.DEFAULT_THREADS
    +
    +  // Timeout for each transaction. If spark does not respond in this much time,
    +  // rollback the transaction
    +  private var transactionTimeout = SparkSinkConfig.DEFAULT_TRANSACTION_TIMEOUT
    +
    +  // Address info to bind on
    +  private var hostname: String = SparkSinkConfig.DEFAULT_HOSTNAME
    +  private var port: Int = 0
    +
    +  // Handle to the server
    +  private var serverOpt: Option[NettyServer] = None
    +
    +  // The handler that handles the callback from Avro
    +  private var handler: Option[SparkAvroCallbackHandler] = None
    +
    +  // Latch that blocks off the Flume framework from wasting 1 thread.
    +  private val blockingLatch = new CountDownLatch(1)
    +
    +  override def start() {
    +    handler = Option(new SparkAvroCallbackHandler(poolSize, getChannel, transactionTimeout))
    +    val responder = new SpecificResponder(classOf[SparkFlumeProtocol], handler.get)
    +    // Using the constructor that takes specific thread-pools requires bringing in netty
    +    // dependencies which are being excluded in the build. In practice,
    +    // Netty dependencies are already available on the JVM as Flume would have pulled them in.
    +    serverOpt = Option(new NettyServer(responder, new InetSocketAddress(hostname, port)))
    +    serverOpt.map(server => {
    +      server.start()
    +    })
    +    super.start()
    +  }
    +
    +  override def stop() {
    +    handler.map(callbackHandler => {
    +      callbackHandler.shutdown()
    +    })
    +    serverOpt.map(server => {
    +      server.close()
    +      server.join()
    +    })
    +    blockingLatch.countDown()
    +    super.stop()
    +  }
    +
    +  /**
    +   * @param ctx
    +   */
    +  override def configure(ctx: Context) {
    +    import SparkSinkConfig._
    +    hostname = ctx.getString(CONF_HOSTNAME, DEFAULT_HOSTNAME)
    +    port = Option(ctx.getInteger(CONF_PORT)).
    +      getOrElse(throw new ConfigurationException("The port to bind to must be specified"))
    +    poolSize = ctx.getInteger(THREADS, DEFAULT_THREADS)
    +    transactionTimeout = ctx.getInteger(CONF_TRANSACTION_TIMEOUT, DEFAULT_TRANSACTION_TIMEOUT)
    +  }
    +
    +  override def process(): Status = {
    +    // This method is called in a loop by the Flume framework - block it until the sink is
    +    // stopped to save CPU resources. The sink runner will interrupt this thread when the sink is
    +    // being shut down.
    +    blockingLatch.await()
    +    Status.BACKOFF
    +  }
    +}
    +
    +/**
    + * Class that implements the SparkFlumeProtocol, that is used by the Avro Netty Server to process
    + * requests. Each getEvents, ack and nack call is forwarded to an instance of this class.
    + * @param threads Number of threads to use to process requests.
    + * @param channel The channel that the sink pulls events from
    + * @param transactionTimeout Timeout in millis after which the transaction if not acked by Spark
    + *                           is rolled back.
    + */
    +private class SparkAvroCallbackHandler(val threads: Int, val channel: Channel,
    +  val transactionTimeout: Int) extends SparkFlumeProtocol {
    +  private val LOG = LoggerFactory.getLogger(classOf[SparkAvroCallbackHandler])
    +  val transactionExecutorOpt = Option(Executors.newFixedThreadPool(threads,
    +    new ThreadFactoryBuilder().setDaemon(true)
    +      .setNameFormat("Spark Sink Processor Thread - %d").build()))
    +  private val processorMap = new ConcurrentHashMap[CharSequence, TransactionProcessor]()
    +  // This sink will not persist sequence numbers and reuses them if it gets restarted.
    +  // So it is possible to commit a transaction which may have been meant for the sink before the
    +  // restart.
    +  // Since the new txn may not have the same sequence number we must guard against accidentally
    +  // committing a new transaction. To reduce the probability of that happening a random string is
    +  // prepended to the sequence number. Does not change for life of sink
    +  private val seqBase = RandomStringUtils.randomAlphanumeric(8)
    +  private val seqCounter = new AtomicLong(0)
    +
    +  /**
    +   * Returns a bunch of events to Spark over Avro RPC.
    +   * @param n Maximum number of events to return in a batch
    +   * @return [[EventBatch]] instance that has a sequence number and an array of at most n events
    +   */
    +  override def getEventBatch(n: Int): EventBatch = {
    +    val sequenceNumber = seqBase + seqCounter.incrementAndGet()
    +    val processor = new TransactionProcessor(channel, sequenceNumber,
    +      n, transactionTimeout, this)
    +    transactionExecutorOpt.map(executor => {
    +      executor.submit(processor)
    +    })
    +    // Wait until a batch is available - can be null if some error was thrown
    +    processor.getEventBatch match {
    +      case ErrorEventBatch => throw new FlumeException("Something went wrong. No events" +
    +        " retrieved from channel.")
    +      case eventBatch: EventBatch =>
    +        processorMap.put(sequenceNumber, processor)
    +        if (LOG.isDebugEnabled()) {
    +          LOG.debug("Sent " + eventBatch.getEvents.size() +
    +            " events with sequence number: " + eventBatch.getSequenceNumber)
    +        }
    +        eventBatch
    +    }
    +  }
    +
    +  /**
    +   * Called by Spark to indicate successful commit of a batch
    +   * @param sequenceNumber The sequence number of the event batch that was successful
    +   */
    +  override def ack(sequenceNumber: CharSequence): Void = {
    +    completeTransaction(sequenceNumber, success = true)
    +    null
    +  }
    +
    +  /**
    +   * Called by Spark to indicate failed commit of a batch
    +   * @param sequenceNumber The sequence number of the event batch that failed
    +   * @return
    +   */
    +  override def nack(sequenceNumber: CharSequence): Void = {
    +    completeTransaction(sequenceNumber, success = false)
    +    LOG.info("Spark failed to commit transaction. Will reattempt events.")
    +    null
    +  }
    +
    +  /**
    +   * Helper method to commit or rollback a transaction.
    +   * @param sequenceNumber The sequence number of the batch that was completed
    +   * @param success Whether the batch was successful or not.
    +   */
    +  private def completeTransaction(sequenceNumber: CharSequence, success: Boolean) {
    +    Option(removeAndGetProcessor(sequenceNumber)).map(processor => {
    +      processor.batchProcessed(success)
    +    })
    +  }
    +
    +  /**
    +   * Helper method to remove the TxnProcessor for a Sequence Number. Can be used to avoid a leak.
    +   * @param sequenceNumber
    +   * @return The transaction processor for the corresponding batch. Note that this instance is no
    +   *         longer tracked and the caller is responsible for that txn processor.
    +   */
    +  private[flume] def removeAndGetProcessor(sequenceNumber: CharSequence): TransactionProcessor = {
    +    processorMap.remove(sequenceNumber.toString) // The toString is required!
    +  }
    +
    +  /**
    +   * Shuts down the executor used to process transactions.
    +   */
    +  def shutdown() {
    +    transactionExecutorOpt.map(executor => {
    +      executor.shutdownNow()
    +    })
    +  }
    +}
    +
    +/**
    + * Object representing an empty batch returned by the txn processor due to some error.
    + */
    +case object ErrorEventBatch extends EventBatch
    --- End diff --
    
    Actually the Option[EventBatch] would work equally well. We simply throw an exception in the case where it is None and let Avro IPC deal with letting the streaming side know.


---
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 infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] spark pull request: SPARK-1729. Make Flume pull data from source, ...

Posted by tdas <gi...@git.apache.org>.
Github user tdas commented on a diff in the pull request:

    https://github.com/apache/spark/pull/807#discussion_r13466097
  
    --- Diff: external/flume-sink/src/main/scala/org/apache/spark/flume/sink/SparkSink.scala ---
    @@ -0,0 +1,392 @@
    +/*
    + * 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.flume.sink
    +
    +import org.apache.flume.sink.AbstractSink
    +import java.util.concurrent.locks.ReentrantLock
    +import org.apache.flume.Sink.Status
    +import org.apache.spark.flume.{SparkSinkEvent, EventBatch, SparkFlumeProtocol}
    +import scala.util.control.Breaks
    +import java.nio.ByteBuffer
    +import org.apache.flume.{FlumeException, Context}
    +import org.slf4j.LoggerFactory
    +import java.util.concurrent.atomic.AtomicLong
    +import org.apache.commons.lang.RandomStringUtils
    +import java.util.concurrent._
    +import java.util
    +import org.apache.flume.conf.{ConfigurationException, Configurable}
    +import com.google.common.util.concurrent.ThreadFactoryBuilder
    +import org.apache.avro.ipc.NettyServer
    +import org.apache.avro.ipc.specific.SpecificResponder
    +import java.net.InetSocketAddress
    +
    +class SparkSink() extends AbstractSink with Configurable {
    --- End diff --
    
    Scala style nit: no need for parenthesis when no parameter present


---
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 infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] spark pull request: SPARK-1729. Make Flume pull data from source, ...

Posted by tdas <gi...@git.apache.org>.
Github user tdas commented on a diff in the pull request:

    https://github.com/apache/spark/pull/807#discussion_r13834950
  
    --- Diff: external/flume-sink/src/main/scala/org/apache/spark/flume/sink/SparkSink.scala ---
    @@ -0,0 +1,432 @@
    +/*
    + * 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.flume.sink
    +
    +import java.net.InetSocketAddress
    +import java.nio.ByteBuffer
    +import java.util
    +import java.util.concurrent._
    +import java.util.concurrent.atomic.AtomicLong
    +
    +import scala.util.control.Breaks
    +
    +import com.google.common.util.concurrent.ThreadFactoryBuilder
    +import org.apache.avro.ipc.NettyServer
    +import org.apache.avro.ipc.specific.SpecificResponder
    +import org.apache.commons.lang.RandomStringUtils
    +import org.apache.flume.Sink.Status
    +import org.apache.flume.conf.{ConfigurationException, Configurable}
    +import org.apache.flume.sink.AbstractSink
    +import org.apache.flume.{Channel, Transaction, FlumeException, Context}
    +import org.slf4j.LoggerFactory
    +
    +import org.apache.spark.flume.{SparkSinkEvent, EventBatch, SparkFlumeProtocol}
    +
    +/**
    + * A sink that uses Avro RPC to run a server that can be polled by Spark's
    + * FlumePollingInputDStream. This sink has the following configuration parameters:
    + *
    + * hostname - The hostname to bind to. Default: 0.0.0.0
    + * port - The port to bind to. (No default - mandatory)
    + * timeout - Time in seconds after which a transaction is rolled back,
    + * if an ACK is not received from Spark within that time
    + * threads - Number of threads to use to receive requests from Spark (Default: 10)
    + *
    + */
    +// Flume forces transactions to be thread-local. So each transaction *must* be committed, or
    +// rolled back from the thread it was originally created in. So each getEvents call from Spark
    +// creates a TransactionProcessor which runs in a new thread, in which the transaction is created
    +// and events are pulled off the channel. Once the events are sent to spark,
    +// that thread is blocked and the TransactionProcessor is saved in a map,
    +// until an ACK or NACK comes back or the transaction times out (after the specified timeout).
    +// When the response comes, the TransactionProcessor is retrieved and then unblocked,
    +// at which point the transaction is committed or rolled back.
    +class SparkSink extends AbstractSink with Configurable {
    +
    +  // Size of the pool to use for holding transaction processors.
    +  private var poolSize: Integer = SparkSinkConfig.DEFAULT_THREADS
    +
    +  // Timeout for each transaction. If spark does not respond in this much time,
    +  // rollback the transaction
    +  private var transactionTimeout = SparkSinkConfig.DEFAULT_TRANSACTION_TIMEOUT
    +
    +  // Address info to bind on
    +  private var hostname: String = SparkSinkConfig.DEFAULT_HOSTNAME
    +  private var port: Int = 0
    +
    +  // Handle to the server
    +  private var serverOpt: Option[NettyServer] = None
    +
    +  // The handler that handles the callback from Avro
    +  private var handler: Option[SparkAvroCallbackHandler] = None
    +
    +  // Latch that blocks off the Flume framework from wasting 1 thread.
    +  private val blockingLatch = new CountDownLatch(1)
    +
    +  override def start() {
    +    handler = Option(new SparkAvroCallbackHandler(poolSize, getChannel, transactionTimeout))
    +    val responder = new SpecificResponder(classOf[SparkFlumeProtocol], handler.get)
    +    // Using the constructor that takes specific thread-pools requires bringing in netty
    +    // dependencies which are being excluded in the build. In practice,
    +    // Netty dependencies are already available on the JVM as Flume would have pulled them in.
    +    serverOpt = Option(new NettyServer(responder, new InetSocketAddress(hostname, port)))
    +    serverOpt.map(server => {
    +      server.start()
    +    })
    +    super.start()
    +  }
    +
    +  override def stop() {
    +    handler.map(callbackHandler => {
    +      callbackHandler.shutdown()
    +    })
    +    serverOpt.map(server => {
    +      server.close()
    +      server.join()
    +    })
    +    blockingLatch.countDown()
    +    super.stop()
    +  }
    +
    +  /**
    +   * @param ctx
    +   */
    +  override def configure(ctx: Context) {
    +    import SparkSinkConfig._
    +    hostname = ctx.getString(CONF_HOSTNAME, DEFAULT_HOSTNAME)
    +    port = Option(ctx.getInteger(CONF_PORT)).
    +      getOrElse(throw new ConfigurationException("The port to bind to must be specified"))
    +    poolSize = ctx.getInteger(THREADS, DEFAULT_THREADS)
    +    transactionTimeout = ctx.getInteger(CONF_TRANSACTION_TIMEOUT, DEFAULT_TRANSACTION_TIMEOUT)
    +  }
    +
    +  override def process(): Status = {
    +    // This method is called in a loop by the Flume framework - block it until the sink is
    +    // stopped to save CPU resources. The sink runner will interrupt this thread when the sink is
    +    // being shut down.
    +    blockingLatch.await()
    +    Status.BACKOFF
    +  }
    +}
    +
    +/**
    + * Class that implements the SparkFlumeProtocol, that is used by the Avro Netty Server to process
    + * requests. Each getEvents, ack and nack call is forwarded to an instance of this class.
    + * @param threads Number of threads to use to process requests.
    + * @param channel The channel that the sink pulls events from
    + * @param transactionTimeout Timeout in millis after which the transaction if not acked by Spark
    + *                           is rolled back.
    + */
    +private class SparkAvroCallbackHandler(val threads: Int, val channel: Channel,
    +  val transactionTimeout: Int) extends SparkFlumeProtocol {
    +  private val LOG = LoggerFactory.getLogger(classOf[SparkAvroCallbackHandler])
    +  val transactionExecutorOpt = Option(Executors.newFixedThreadPool(threads,
    +    new ThreadFactoryBuilder().setDaemon(true)
    +      .setNameFormat("Spark Sink Processor Thread - %d").build()))
    +  private val processorMap = new ConcurrentHashMap[CharSequence, TransactionProcessor]()
    +  // This sink will not persist sequence numbers and reuses them if it gets restarted.
    +  // So it is possible to commit a transaction which may have been meant for the sink before the
    +  // restart.
    +  // Since the new txn may not have the same sequence number we must guard against accidentally
    +  // committing a new transaction. To reduce the probability of that happening a random string is
    +  // prepended to the sequence number. Does not change for life of sink
    +  private val seqBase = RandomStringUtils.randomAlphanumeric(8)
    +  private val seqCounter = new AtomicLong(0)
    +
    +  /**
    +   * Returns a bunch of events to Spark over Avro RPC.
    +   * @param n Maximum number of events to return in a batch
    +   * @return [[EventBatch]] instance that has a sequence number and an array of at most n events
    +   */
    +  override def getEventBatch(n: Int): EventBatch = {
    +    val sequenceNumber = seqBase + seqCounter.incrementAndGet()
    +    val processor = new TransactionProcessor(channel, sequenceNumber,
    +      n, transactionTimeout, this)
    +    transactionExecutorOpt.map(executor => {
    +      executor.submit(processor)
    +    })
    +    // Wait until a batch is available - can be null if some error was thrown
    +    processor.getEventBatch match {
    +      case ErrorEventBatch => throw new FlumeException("Something went wrong. No events" +
    +        " retrieved from channel.")
    +      case eventBatch: EventBatch =>
    +        processorMap.put(sequenceNumber, processor)
    +        if (LOG.isDebugEnabled()) {
    +          LOG.debug("Sent " + eventBatch.getEvents.size() +
    +            " events with sequence number: " + eventBatch.getSequenceNumber)
    +        }
    +        eventBatch
    +    }
    +  }
    +
    +  /**
    +   * Called by Spark to indicate successful commit of a batch
    +   * @param sequenceNumber The sequence number of the event batch that was successful
    +   */
    +  override def ack(sequenceNumber: CharSequence): Void = {
    +    completeTransaction(sequenceNumber, success = true)
    +    null
    +  }
    +
    +  /**
    +   * Called by Spark to indicate failed commit of a batch
    +   * @param sequenceNumber The sequence number of the event batch that failed
    +   * @return
    +   */
    +  override def nack(sequenceNumber: CharSequence): Void = {
    +    completeTransaction(sequenceNumber, success = false)
    +    LOG.info("Spark failed to commit transaction. Will reattempt events.")
    +    null
    +  }
    +
    +  /**
    +   * Helper method to commit or rollback a transaction.
    +   * @param sequenceNumber The sequence number of the batch that was completed
    +   * @param success Whether the batch was successful or not.
    +   */
    +  private def completeTransaction(sequenceNumber: CharSequence, success: Boolean) {
    +    Option(removeAndGetProcessor(sequenceNumber)).map(processor => {
    +      processor.batchProcessed(success)
    +    })
    +  }
    +
    +  /**
    +   * Helper method to remove the TxnProcessor for a Sequence Number. Can be used to avoid a leak.
    +   * @param sequenceNumber
    +   * @return The transaction processor for the corresponding batch. Note that this instance is no
    +   *         longer tracked and the caller is responsible for that txn processor.
    +   */
    +  private[flume] def removeAndGetProcessor(sequenceNumber: CharSequence): TransactionProcessor = {
    +    processorMap.remove(sequenceNumber.toString) // The toString is required!
    +  }
    +
    +  /**
    +   * Shuts down the executor used to process transactions.
    +   */
    +  def shutdown() {
    +    transactionExecutorOpt.map(executor => {
    +      executor.shutdownNow()
    +    })
    +  }
    +}
    +
    +/**
    + * Object representing an empty batch returned by the txn processor due to some error.
    + */
    +case object ErrorEventBatch extends EventBatch
    +
    +// Flume forces transactions to be thread-local (horrible, I know!)
    +// So the sink basically spawns a new thread to pull the events out within a transaction.
    +// The thread fills in the event batch object that is set before the thread is scheduled.
    +// After filling it in, the thread waits on a condition - which is released only
    +// when the success message comes back for the specific sequence number for that event batch.
    +/**
    + * This class represents a transaction on the Flume channel. This class runs a separate thread
    + * which owns the transaction. The thread is blocked until the success call for that transaction
    + * comes back with an ACK or NACK.
    + * @param channel The channel from which to pull events
    + * @param seqNum The sequence number to use for the transaction. Must be unique
    + * @param maxBatchSize The maximum number of events to process per batch
    + * @param transactionTimeout Time in seconds after which a transaction must be rolled back
    + *                           without waiting for an ACK from Spark
    + * @param parent The parent [[SparkAvroCallbackHandler]] instance, for reporting timeouts
    + */
    +private class TransactionProcessor(val channel: Channel, val seqNum: String,
    +  var maxBatchSize: Int, val transactionTimeout: Int,
    +  val parent: SparkAvroCallbackHandler) extends Callable[Void] {
    +
    +  private val LOG = LoggerFactory.getLogger(classOf[TransactionProcessor])
    +
    +  // If a real batch is not returned, we always have to return an error batch.
    +  @volatile private var eventBatch: EventBatch = ErrorEventBatch
    +
    +  // Synchronization primitives
    +  val batchGeneratedLatch = new CountDownLatch(1)
    +  val batchAckLatch = new CountDownLatch(1)
    +
    +  // Sanity check to ensure we don't loop like crazy
    +  val totalAttemptsToRemoveFromChannel = Int.MaxValue / 2
    +
    +  // OK to use volatile, since the change would only make this true (otherwise it will be
    +  // changed to false - we never apply a negation operation to this) - which means the transaction
    +  // succeeded.
    +  @volatile private var batchSuccess = false
    +
    +  // The transaction that this processor would handle
    +  var txOpt: Option[Transaction] = None
    +
    +  /**
    +   * Get an event batch from the channel. This method will block until a batch of events is
    +   * available from the channel. If no events are available after a large number of attempts of
    +   * polling the channel, this method will return [[ErrorEventBatch]].
    +   *
    +   * @return An [[EventBatch]] instance with sequence number set to [[seqNum]], filled with a
    +   *         maximum of [[maxBatchSize]] events
    +   */
    +  def getEventBatch: EventBatch = {
    +    batchGeneratedLatch.await()
    +    eventBatch
    +  }
    +
    +  /**
    +   * This method is to be called by the sink when it receives an ACK or NACK from Spark. This
    +   * method is a no-op if it is called after [[transactionTimeout]] has expired since
    +   * [[getEventBatch]] returned a batch of events.
    +   * @param success True if an ACK was received and the transaction should be committed, else false.
    +   */
    +  def batchProcessed(success: Boolean) {
    +    if (LOG.isDebugEnabled) {
    +      LOG.debug("Batch processed for sequence number: " + seqNum)
    +    }
    +    batchSuccess = success
    +    batchAckLatch.countDown()
    +  }
    +
    +  /**
    +   * Populates events into the event batch. If the batch cannot be populated,
    +   * this method will not set the event batch which will stay [[ErrorEventBatch]]
    +   */
    +  private def populateEvents() {
    +    try {
    +      txOpt = Option(channel.getTransaction)
    --- End diff --
    
    Can getTransaction ever return null? If so, then we need a better way to handle it. Right now what will happen is that  the following map function will be ignored and no eventBatch will be assigned, and no exceptions either. Nothing will be present in the log either, except on the Spark streaming side there will be a timeout to get the next batch (without any reason in any log )


---
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 infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] spark pull request: SPARK-1729. Make Flume pull data from source, ...

Posted by harishreedharan <gi...@git.apache.org>.
Github user harishreedharan commented on a diff in the pull request:

    https://github.com/apache/spark/pull/807#discussion_r13838603
  
    --- Diff: external/flume-sink/src/main/scala/org/apache/spark/flume/sink/SparkSink.scala ---
    @@ -0,0 +1,432 @@
    +/*
    + * 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.flume.sink
    +
    +import java.net.InetSocketAddress
    +import java.nio.ByteBuffer
    +import java.util
    +import java.util.concurrent._
    +import java.util.concurrent.atomic.AtomicLong
    +
    +import scala.util.control.Breaks
    +
    +import com.google.common.util.concurrent.ThreadFactoryBuilder
    +import org.apache.avro.ipc.NettyServer
    +import org.apache.avro.ipc.specific.SpecificResponder
    +import org.apache.commons.lang.RandomStringUtils
    +import org.apache.flume.Sink.Status
    +import org.apache.flume.conf.{ConfigurationException, Configurable}
    +import org.apache.flume.sink.AbstractSink
    +import org.apache.flume.{Channel, Transaction, FlumeException, Context}
    +import org.slf4j.LoggerFactory
    +
    +import org.apache.spark.flume.{SparkSinkEvent, EventBatch, SparkFlumeProtocol}
    +
    +/**
    + * A sink that uses Avro RPC to run a server that can be polled by Spark's
    + * FlumePollingInputDStream. This sink has the following configuration parameters:
    + *
    + * hostname - The hostname to bind to. Default: 0.0.0.0
    + * port - The port to bind to. (No default - mandatory)
    + * timeout - Time in seconds after which a transaction is rolled back,
    + * if an ACK is not received from Spark within that time
    + * threads - Number of threads to use to receive requests from Spark (Default: 10)
    + *
    + */
    +// Flume forces transactions to be thread-local. So each transaction *must* be committed, or
    +// rolled back from the thread it was originally created in. So each getEvents call from Spark
    +// creates a TransactionProcessor which runs in a new thread, in which the transaction is created
    +// and events are pulled off the channel. Once the events are sent to spark,
    +// that thread is blocked and the TransactionProcessor is saved in a map,
    +// until an ACK or NACK comes back or the transaction times out (after the specified timeout).
    +// When the response comes, the TransactionProcessor is retrieved and then unblocked,
    +// at which point the transaction is committed or rolled back.
    +class SparkSink extends AbstractSink with Configurable {
    +
    +  // Size of the pool to use for holding transaction processors.
    +  private var poolSize: Integer = SparkSinkConfig.DEFAULT_THREADS
    +
    +  // Timeout for each transaction. If spark does not respond in this much time,
    +  // rollback the transaction
    +  private var transactionTimeout = SparkSinkConfig.DEFAULT_TRANSACTION_TIMEOUT
    +
    +  // Address info to bind on
    +  private var hostname: String = SparkSinkConfig.DEFAULT_HOSTNAME
    +  private var port: Int = 0
    +
    +  // Handle to the server
    +  private var serverOpt: Option[NettyServer] = None
    +
    +  // The handler that handles the callback from Avro
    +  private var handler: Option[SparkAvroCallbackHandler] = None
    +
    +  // Latch that blocks off the Flume framework from wasting 1 thread.
    +  private val blockingLatch = new CountDownLatch(1)
    +
    +  override def start() {
    +    handler = Option(new SparkAvroCallbackHandler(poolSize, getChannel, transactionTimeout))
    +    val responder = new SpecificResponder(classOf[SparkFlumeProtocol], handler.get)
    +    // Using the constructor that takes specific thread-pools requires bringing in netty
    +    // dependencies which are being excluded in the build. In practice,
    +    // Netty dependencies are already available on the JVM as Flume would have pulled them in.
    +    serverOpt = Option(new NettyServer(responder, new InetSocketAddress(hostname, port)))
    +    serverOpt.map(server => {
    +      server.start()
    +    })
    +    super.start()
    +  }
    +
    +  override def stop() {
    +    handler.map(callbackHandler => {
    +      callbackHandler.shutdown()
    +    })
    +    serverOpt.map(server => {
    +      server.close()
    +      server.join()
    +    })
    +    blockingLatch.countDown()
    +    super.stop()
    +  }
    +
    +  /**
    +   * @param ctx
    +   */
    +  override def configure(ctx: Context) {
    +    import SparkSinkConfig._
    +    hostname = ctx.getString(CONF_HOSTNAME, DEFAULT_HOSTNAME)
    +    port = Option(ctx.getInteger(CONF_PORT)).
    +      getOrElse(throw new ConfigurationException("The port to bind to must be specified"))
    +    poolSize = ctx.getInteger(THREADS, DEFAULT_THREADS)
    +    transactionTimeout = ctx.getInteger(CONF_TRANSACTION_TIMEOUT, DEFAULT_TRANSACTION_TIMEOUT)
    +  }
    +
    +  override def process(): Status = {
    +    // This method is called in a loop by the Flume framework - block it until the sink is
    +    // stopped to save CPU resources. The sink runner will interrupt this thread when the sink is
    +    // being shut down.
    +    blockingLatch.await()
    +    Status.BACKOFF
    +  }
    +}
    +
    +/**
    + * Class that implements the SparkFlumeProtocol, that is used by the Avro Netty Server to process
    + * requests. Each getEvents, ack and nack call is forwarded to an instance of this class.
    + * @param threads Number of threads to use to process requests.
    + * @param channel The channel that the sink pulls events from
    + * @param transactionTimeout Timeout in millis after which the transaction if not acked by Spark
    + *                           is rolled back.
    + */
    +private class SparkAvroCallbackHandler(val threads: Int, val channel: Channel,
    +  val transactionTimeout: Int) extends SparkFlumeProtocol {
    +  private val LOG = LoggerFactory.getLogger(classOf[SparkAvroCallbackHandler])
    +  val transactionExecutorOpt = Option(Executors.newFixedThreadPool(threads,
    +    new ThreadFactoryBuilder().setDaemon(true)
    +      .setNameFormat("Spark Sink Processor Thread - %d").build()))
    +  private val processorMap = new ConcurrentHashMap[CharSequence, TransactionProcessor]()
    +  // This sink will not persist sequence numbers and reuses them if it gets restarted.
    +  // So it is possible to commit a transaction which may have been meant for the sink before the
    +  // restart.
    +  // Since the new txn may not have the same sequence number we must guard against accidentally
    +  // committing a new transaction. To reduce the probability of that happening a random string is
    +  // prepended to the sequence number. Does not change for life of sink
    +  private val seqBase = RandomStringUtils.randomAlphanumeric(8)
    +  private val seqCounter = new AtomicLong(0)
    +
    +  /**
    +   * Returns a bunch of events to Spark over Avro RPC.
    +   * @param n Maximum number of events to return in a batch
    +   * @return [[EventBatch]] instance that has a sequence number and an array of at most n events
    +   */
    +  override def getEventBatch(n: Int): EventBatch = {
    +    val sequenceNumber = seqBase + seqCounter.incrementAndGet()
    +    val processor = new TransactionProcessor(channel, sequenceNumber,
    +      n, transactionTimeout, this)
    +    transactionExecutorOpt.map(executor => {
    +      executor.submit(processor)
    +    })
    +    // Wait until a batch is available - can be null if some error was thrown
    +    processor.getEventBatch match {
    +      case ErrorEventBatch => throw new FlumeException("Something went wrong. No events" +
    +        " retrieved from channel.")
    +      case eventBatch: EventBatch =>
    +        processorMap.put(sequenceNumber, processor)
    +        if (LOG.isDebugEnabled()) {
    +          LOG.debug("Sent " + eventBatch.getEvents.size() +
    +            " events with sequence number: " + eventBatch.getSequenceNumber)
    +        }
    +        eventBatch
    +    }
    +  }
    +
    +  /**
    +   * Called by Spark to indicate successful commit of a batch
    +   * @param sequenceNumber The sequence number of the event batch that was successful
    +   */
    +  override def ack(sequenceNumber: CharSequence): Void = {
    +    completeTransaction(sequenceNumber, success = true)
    +    null
    +  }
    +
    +  /**
    +   * Called by Spark to indicate failed commit of a batch
    +   * @param sequenceNumber The sequence number of the event batch that failed
    +   * @return
    +   */
    +  override def nack(sequenceNumber: CharSequence): Void = {
    +    completeTransaction(sequenceNumber, success = false)
    +    LOG.info("Spark failed to commit transaction. Will reattempt events.")
    +    null
    +  }
    +
    +  /**
    +   * Helper method to commit or rollback a transaction.
    +   * @param sequenceNumber The sequence number of the batch that was completed
    +   * @param success Whether the batch was successful or not.
    +   */
    +  private def completeTransaction(sequenceNumber: CharSequence, success: Boolean) {
    +    Option(removeAndGetProcessor(sequenceNumber)).map(processor => {
    +      processor.batchProcessed(success)
    +    })
    +  }
    +
    +  /**
    +   * Helper method to remove the TxnProcessor for a Sequence Number. Can be used to avoid a leak.
    +   * @param sequenceNumber
    +   * @return The transaction processor for the corresponding batch. Note that this instance is no
    +   *         longer tracked and the caller is responsible for that txn processor.
    +   */
    +  private[flume] def removeAndGetProcessor(sequenceNumber: CharSequence): TransactionProcessor = {
    +    processorMap.remove(sequenceNumber.toString) // The toString is required!
    +  }
    +
    +  /**
    +   * Shuts down the executor used to process transactions.
    +   */
    +  def shutdown() {
    +    transactionExecutorOpt.map(executor => {
    +      executor.shutdownNow()
    +    })
    +  }
    +}
    +
    +/**
    + * Object representing an empty batch returned by the txn processor due to some error.
    + */
    +case object ErrorEventBatch extends EventBatch
    --- End diff --
    
    Makes sense. Will do.


---
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 infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] spark pull request: SPARK-1729. Make Flume pull data from source, ...

Posted by harishreedharan <gi...@git.apache.org>.
Github user harishreedharan commented on a diff in the pull request:

    https://github.com/apache/spark/pull/807#discussion_r13471458
  
    --- Diff: external/flume-sink/src/main/scala/org/apache/spark/flume/sink/SparkSink.scala ---
    @@ -0,0 +1,392 @@
    +/*
    + * 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.flume.sink
    +
    +import org.apache.flume.sink.AbstractSink
    +import java.util.concurrent.locks.ReentrantLock
    +import org.apache.flume.Sink.Status
    +import org.apache.spark.flume.{SparkSinkEvent, EventBatch, SparkFlumeProtocol}
    +import scala.util.control.Breaks
    +import java.nio.ByteBuffer
    +import org.apache.flume.{FlumeException, Context}
    +import org.slf4j.LoggerFactory
    +import java.util.concurrent.atomic.AtomicLong
    +import org.apache.commons.lang.RandomStringUtils
    +import java.util.concurrent._
    +import java.util
    +import org.apache.flume.conf.{ConfigurationException, Configurable}
    +import com.google.common.util.concurrent.ThreadFactoryBuilder
    +import org.apache.avro.ipc.NettyServer
    +import org.apache.avro.ipc.specific.SpecificResponder
    +import java.net.InetSocketAddress
    +
    +class SparkSink() extends AbstractSink with Configurable {
    +  private val LOG = LoggerFactory.getLogger(this.getClass)
    +  private val lock = new ReentrantLock()
    +  private val blockingCondition = lock.newCondition()
    +
    +  // This sink will not persist sequence numbers and reuses them if it gets restarted.
    +  // So it is possible to commit a transaction which may have been meant for the sink before the
    +  // restart.
    +  // Since the new txn may not have the same sequence number we must guard against accidentally
    +  // committing
    +  // a new transaction. To reduce the probability of that happening a random string is prepended
    +  // to the sequence number.
    +  // Does not change for life of sink
    +  private val seqBase = RandomStringUtils.randomAlphanumeric(8)
    +  // Incremented for each transaction
    +  private val seqNum = new AtomicLong(0)
    +
    +  private var transactionExecutorOpt: Option[ExecutorService] = None
    +
    +  private var numProcessors: Integer = SparkSinkConfig.DEFAULT_PROCESSOR_COUNT
    +  private var transactionTimeout = SparkSinkConfig.DEFAULT_TRANSACTION_TIMEOUT
    +
    +  private val processorMap = new ConcurrentHashMap[CharSequence, TransactionProcessor]()
    +
    +  private var processorFactory: Option[SparkHandlerFactory] = None
    +  private var hostname: String = SparkSinkConfig.DEFAULT_HOSTNAME
    +  private var port: Int = 0
    +  private var maxThreads: Int = SparkSinkConfig.DEFAULT_MAX_THREADS
    +  private var serverOpt: Option[NettyServer] = None
    +  private var running = false
    +
    +  override def start() {
    +    transactionExecutorOpt = Option(Executors.newFixedThreadPool(numProcessors,
    +      new ThreadFactoryBuilder().setDaemon(true)
    +        .setNameFormat("Spark Sink, " + getName + " Processor Thread - %d").build()))
    +
    +    processorFactory = Option(new SparkHandlerFactory(numProcessors))
    +
    +    val responder = new SpecificResponder(classOf[SparkFlumeProtocol], new AvroCallbackHandler())
    +
    +    // Using the constructor that takes specific thread-pools requires bringing in netty
    +    // dependencies which are being excluded in the build. In practice,
    +    // Netty dependencies are already available on the JVM as Flume would have pulled them in.
    +    serverOpt = Option(new NettyServer(responder, new InetSocketAddress(hostname, port)))
    +
    +    serverOpt.map(server => server.start())
    +    lock.lock()
    +    try {
    +      running = true
    +    } finally {
    +      lock.unlock()
    +    }
    +    super.start()
    +  }
    +
    +  override def stop() {
    +    transactionExecutorOpt.map(executor => executor.shutdownNow())
    +    serverOpt.map(server => {
    +      server.close()
    +      server.join()
    +    })
    +    lock.lock()
    +    try {
    +      running = false
    +      blockingCondition.signalAll()
    +    } finally {
    +      lock.unlock()
    +    }
    +  }
    +
    +  override def configure(ctx: Context) {
    +    import SparkSinkConfig._
    +    hostname = ctx.getString(CONF_HOSTNAME, DEFAULT_HOSTNAME)
    +    val portOpt = Option(ctx.getInteger(CONF_PORT))
    +    if(portOpt.isDefined) {
    +      port = portOpt.get
    +    } else {
    +      throw new ConfigurationException("The Port to bind must be specified")
    +    }
    --- End diff --
    
    Ha, thanks!


---
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 infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] spark pull request: SPARK-1729. Make Flume pull data from source, ...

Posted by harishreedharan <gi...@git.apache.org>.
Github user harishreedharan commented on the pull request:

    https://github.com/apache/spark/pull/807#issuecomment-43526213
  
    The latest commit should fix the build issue.


---
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 infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] spark pull request: SPARK-1729. Make Flume pull data from source, ...

Posted by harishreedharan <gi...@git.apache.org>.
Github user harishreedharan commented on a diff in the pull request:

    https://github.com/apache/spark/pull/807#discussion_r13823887
  
    --- Diff: external/flume/src/main/scala/org/apache/spark/streaming/flume/EventTransformer.scala ---
    @@ -0,0 +1,72 @@
    +/*
    + * 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.streaming.flume
    +
    +import java.io.{ObjectOutput, ObjectInput}
    +
    +import scala.collection.JavaConversions._
    +
    +import org.apache.spark.util.Utils
    +import org.apache.spark.Logging
    +
    +/**
    + * A simple object that provides the implementation of readExternal and writeExternal for both
    + * the wrapper classes for Flume-style Events.
    + */
    +object EventTransformer extends Logging {
    +  def readExternal(in: ObjectInput): (java.util.HashMap[CharSequence, CharSequence],
    +    Array[Byte]) = {
    +    val bodyLength = in.readInt()
    +    val bodyBuff = new Array[Byte](bodyLength)
    +    in.read(bodyBuff)
    +
    +    val numHeaders = in.readInt()
    +    val headers = new java.util.HashMap[CharSequence, CharSequence]
    +
    +    for (i <- 0 until numHeaders) {
    +      val keyLength = in.readInt()
    +      val keyBuff = new Array[Byte](keyLength)
    +      in.read(keyBuff)
    --- End diff --
    
    This is just currently existing code refactored to a new class. I'd rather not change it unless absolutely required.


---
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 infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] spark pull request: SPARK-1729. Make Flume pull data from source, ...

Posted by harishreedharan <gi...@git.apache.org>.
Github user harishreedharan commented on a diff in the pull request:

    https://github.com/apache/spark/pull/807#discussion_r13838567
  
    --- Diff: external/flume-sink/src/main/scala/org/apache/spark/flume/sink/SparkSink.scala ---
    @@ -0,0 +1,432 @@
    +/*
    + * 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.flume.sink
    +
    +import java.net.InetSocketAddress
    +import java.nio.ByteBuffer
    +import java.util
    +import java.util.concurrent._
    +import java.util.concurrent.atomic.AtomicLong
    +
    +import scala.util.control.Breaks
    +
    +import com.google.common.util.concurrent.ThreadFactoryBuilder
    +import org.apache.avro.ipc.NettyServer
    +import org.apache.avro.ipc.specific.SpecificResponder
    +import org.apache.commons.lang.RandomStringUtils
    +import org.apache.flume.Sink.Status
    +import org.apache.flume.conf.{ConfigurationException, Configurable}
    +import org.apache.flume.sink.AbstractSink
    +import org.apache.flume.{Channel, Transaction, FlumeException, Context}
    +import org.slf4j.LoggerFactory
    +
    +import org.apache.spark.flume.{SparkSinkEvent, EventBatch, SparkFlumeProtocol}
    +
    +/**
    + * A sink that uses Avro RPC to run a server that can be polled by Spark's
    + * FlumePollingInputDStream. This sink has the following configuration parameters:
    + *
    + * hostname - The hostname to bind to. Default: 0.0.0.0
    + * port - The port to bind to. (No default - mandatory)
    + * timeout - Time in seconds after which a transaction is rolled back,
    + * if an ACK is not received from Spark within that time
    + * threads - Number of threads to use to receive requests from Spark (Default: 10)
    + *
    + */
    +// Flume forces transactions to be thread-local. So each transaction *must* be committed, or
    +// rolled back from the thread it was originally created in. So each getEvents call from Spark
    +// creates a TransactionProcessor which runs in a new thread, in which the transaction is created
    +// and events are pulled off the channel. Once the events are sent to spark,
    +// that thread is blocked and the TransactionProcessor is saved in a map,
    +// until an ACK or NACK comes back or the transaction times out (after the specified timeout).
    +// When the response comes, the TransactionProcessor is retrieved and then unblocked,
    +// at which point the transaction is committed or rolled back.
    +class SparkSink extends AbstractSink with Configurable {
    +
    +  // Size of the pool to use for holding transaction processors.
    +  private var poolSize: Integer = SparkSinkConfig.DEFAULT_THREADS
    +
    +  // Timeout for each transaction. If spark does not respond in this much time,
    +  // rollback the transaction
    +  private var transactionTimeout = SparkSinkConfig.DEFAULT_TRANSACTION_TIMEOUT
    +
    +  // Address info to bind on
    +  private var hostname: String = SparkSinkConfig.DEFAULT_HOSTNAME
    +  private var port: Int = 0
    +
    +  // Handle to the server
    +  private var serverOpt: Option[NettyServer] = None
    +
    +  // The handler that handles the callback from Avro
    +  private var handler: Option[SparkAvroCallbackHandler] = None
    +
    +  // Latch that blocks off the Flume framework from wasting 1 thread.
    +  private val blockingLatch = new CountDownLatch(1)
    +
    +  override def start() {
    +    handler = Option(new SparkAvroCallbackHandler(poolSize, getChannel, transactionTimeout))
    +    val responder = new SpecificResponder(classOf[SparkFlumeProtocol], handler.get)
    +    // Using the constructor that takes specific thread-pools requires bringing in netty
    +    // dependencies which are being excluded in the build. In practice,
    +    // Netty dependencies are already available on the JVM as Flume would have pulled them in.
    +    serverOpt = Option(new NettyServer(responder, new InetSocketAddress(hostname, port)))
    +    serverOpt.map(server => {
    +      server.start()
    +    })
    +    super.start()
    +  }
    +
    +  override def stop() {
    +    handler.map(callbackHandler => {
    +      callbackHandler.shutdown()
    +    })
    +    serverOpt.map(server => {
    +      server.close()
    +      server.join()
    +    })
    +    blockingLatch.countDown()
    +    super.stop()
    +  }
    +
    +  /**
    +   * @param ctx
    +   */
    +  override def configure(ctx: Context) {
    +    import SparkSinkConfig._
    +    hostname = ctx.getString(CONF_HOSTNAME, DEFAULT_HOSTNAME)
    +    port = Option(ctx.getInteger(CONF_PORT)).
    +      getOrElse(throw new ConfigurationException("The port to bind to must be specified"))
    +    poolSize = ctx.getInteger(THREADS, DEFAULT_THREADS)
    +    transactionTimeout = ctx.getInteger(CONF_TRANSACTION_TIMEOUT, DEFAULT_TRANSACTION_TIMEOUT)
    +  }
    +
    +  override def process(): Status = {
    +    // This method is called in a loop by the Flume framework - block it until the sink is
    +    // stopped to save CPU resources. The sink runner will interrupt this thread when the sink is
    +    // being shut down.
    +    blockingLatch.await()
    +    Status.BACKOFF
    +  }
    +}
    +
    +/**
    + * Class that implements the SparkFlumeProtocol, that is used by the Avro Netty Server to process
    + * requests. Each getEvents, ack and nack call is forwarded to an instance of this class.
    + * @param threads Number of threads to use to process requests.
    + * @param channel The channel that the sink pulls events from
    + * @param transactionTimeout Timeout in millis after which the transaction if not acked by Spark
    + *                           is rolled back.
    + */
    +private class SparkAvroCallbackHandler(val threads: Int, val channel: Channel,
    +  val transactionTimeout: Int) extends SparkFlumeProtocol {
    +  private val LOG = LoggerFactory.getLogger(classOf[SparkAvroCallbackHandler])
    +  val transactionExecutorOpt = Option(Executors.newFixedThreadPool(threads,
    +    new ThreadFactoryBuilder().setDaemon(true)
    +      .setNameFormat("Spark Sink Processor Thread - %d").build()))
    +  private val processorMap = new ConcurrentHashMap[CharSequence, TransactionProcessor]()
    +  // This sink will not persist sequence numbers and reuses them if it gets restarted.
    +  // So it is possible to commit a transaction which may have been meant for the sink before the
    +  // restart.
    +  // Since the new txn may not have the same sequence number we must guard against accidentally
    +  // committing a new transaction. To reduce the probability of that happening a random string is
    +  // prepended to the sequence number. Does not change for life of sink
    +  private val seqBase = RandomStringUtils.randomAlphanumeric(8)
    +  private val seqCounter = new AtomicLong(0)
    +
    +  /**
    +   * Returns a bunch of events to Spark over Avro RPC.
    +   * @param n Maximum number of events to return in a batch
    +   * @return [[EventBatch]] instance that has a sequence number and an array of at most n events
    +   */
    +  override def getEventBatch(n: Int): EventBatch = {
    +    val sequenceNumber = seqBase + seqCounter.incrementAndGet()
    +    val processor = new TransactionProcessor(channel, sequenceNumber,
    +      n, transactionTimeout, this)
    +    transactionExecutorOpt.map(executor => {
    +      executor.submit(processor)
    +    })
    +    // Wait until a batch is available - can be null if some error was thrown
    +    processor.getEventBatch match {
    +      case ErrorEventBatch => throw new FlumeException("Something went wrong. No events" +
    +        " retrieved from channel.")
    +      case eventBatch: EventBatch =>
    +        processorMap.put(sequenceNumber, processor)
    +        if (LOG.isDebugEnabled()) {
    +          LOG.debug("Sent " + eventBatch.getEvents.size() +
    +            " events with sequence number: " + eventBatch.getSequenceNumber)
    +        }
    +        eventBatch
    +    }
    +  }
    +
    +  /**
    +   * Called by Spark to indicate successful commit of a batch
    +   * @param sequenceNumber The sequence number of the event batch that was successful
    +   */
    +  override def ack(sequenceNumber: CharSequence): Void = {
    +    completeTransaction(sequenceNumber, success = true)
    +    null
    +  }
    +
    +  /**
    +   * Called by Spark to indicate failed commit of a batch
    +   * @param sequenceNumber The sequence number of the event batch that failed
    +   * @return
    +   */
    +  override def nack(sequenceNumber: CharSequence): Void = {
    +    completeTransaction(sequenceNumber, success = false)
    +    LOG.info("Spark failed to commit transaction. Will reattempt events.")
    +    null
    +  }
    +
    +  /**
    +   * Helper method to commit or rollback a transaction.
    +   * @param sequenceNumber The sequence number of the batch that was completed
    +   * @param success Whether the batch was successful or not.
    +   */
    +  private def completeTransaction(sequenceNumber: CharSequence, success: Boolean) {
    +    Option(removeAndGetProcessor(sequenceNumber)).map(processor => {
    +      processor.batchProcessed(success)
    +    })
    +  }
    +
    +  /**
    +   * Helper method to remove the TxnProcessor for a Sequence Number. Can be used to avoid a leak.
    +   * @param sequenceNumber
    +   * @return The transaction processor for the corresponding batch. Note that this instance is no
    +   *         longer tracked and the caller is responsible for that txn processor.
    +   */
    +  private[flume] def removeAndGetProcessor(sequenceNumber: CharSequence): TransactionProcessor = {
    +    processorMap.remove(sequenceNumber.toString) // The toString is required!
    +  }
    +
    +  /**
    +   * Shuts down the executor used to process transactions.
    +   */
    +  def shutdown() {
    +    transactionExecutorOpt.map(executor => {
    +      executor.shutdownNow()
    +    })
    +  }
    +}
    +
    +/**
    + * Object representing an empty batch returned by the txn processor due to some error.
    + */
    +case object ErrorEventBatch extends EventBatch
    +
    +// Flume forces transactions to be thread-local (horrible, I know!)
    +// So the sink basically spawns a new thread to pull the events out within a transaction.
    +// The thread fills in the event batch object that is set before the thread is scheduled.
    +// After filling it in, the thread waits on a condition - which is released only
    +// when the success message comes back for the specific sequence number for that event batch.
    +/**
    + * This class represents a transaction on the Flume channel. This class runs a separate thread
    + * which owns the transaction. The thread is blocked until the success call for that transaction
    + * comes back with an ACK or NACK.
    + * @param channel The channel from which to pull events
    + * @param seqNum The sequence number to use for the transaction. Must be unique
    + * @param maxBatchSize The maximum number of events to process per batch
    + * @param transactionTimeout Time in seconds after which a transaction must be rolled back
    + *                           without waiting for an ACK from Spark
    + * @param parent The parent [[SparkAvroCallbackHandler]] instance, for reporting timeouts
    + */
    +private class TransactionProcessor(val channel: Channel, val seqNum: String,
    +  var maxBatchSize: Int, val transactionTimeout: Int,
    +  val parent: SparkAvroCallbackHandler) extends Callable[Void] {
    +
    +  private val LOG = LoggerFactory.getLogger(classOf[TransactionProcessor])
    +
    +  // If a real batch is not returned, we always have to return an error batch.
    +  @volatile private var eventBatch: EventBatch = ErrorEventBatch
    +
    +  // Synchronization primitives
    +  val batchGeneratedLatch = new CountDownLatch(1)
    +  val batchAckLatch = new CountDownLatch(1)
    +
    +  // Sanity check to ensure we don't loop like crazy
    +  val totalAttemptsToRemoveFromChannel = Int.MaxValue / 2
    +
    +  // OK to use volatile, since the change would only make this true (otherwise it will be
    +  // changed to false - we never apply a negation operation to this) - which means the transaction
    +  // succeeded.
    +  @volatile private var batchSuccess = false
    +
    +  // The transaction that this processor would handle
    +  var txOpt: Option[Transaction] = None
    +
    +  /**
    +   * Get an event batch from the channel. This method will block until a batch of events is
    +   * available from the channel. If no events are available after a large number of attempts of
    +   * polling the channel, this method will return [[ErrorEventBatch]].
    +   *
    +   * @return An [[EventBatch]] instance with sequence number set to [[seqNum]], filled with a
    +   *         maximum of [[maxBatchSize]] events
    +   */
    +  def getEventBatch: EventBatch = {
    +    batchGeneratedLatch.await()
    +    eventBatch
    +  }
    +
    +  /**
    +   * This method is to be called by the sink when it receives an ACK or NACK from Spark. This
    +   * method is a no-op if it is called after [[transactionTimeout]] has expired since
    +   * [[getEventBatch]] returned a batch of events.
    +   * @param success True if an ACK was received and the transaction should be committed, else false.
    +   */
    +  def batchProcessed(success: Boolean) {
    +    if (LOG.isDebugEnabled) {
    +      LOG.debug("Batch processed for sequence number: " + seqNum)
    +    }
    +    batchSuccess = success
    +    batchAckLatch.countDown()
    +  }
    +
    +  /**
    +   * Populates events into the event batch. If the batch cannot be populated,
    +   * this method will not set the event batch which will stay [[ErrorEventBatch]]
    +   */
    +  private def populateEvents() {
    +    try {
    +      txOpt = Option(channel.getTransaction)
    +      txOpt.map(tx => {
    +        tx.begin()
    +        val events = new util.ArrayList[SparkSinkEvent](maxBatchSize)
    +        val loop = new Breaks
    +        var gotEventsInThisTxn = false
    +        var loopCounter: Int = 0
    +        loop.breakable {
    +          while (events.size() < maxBatchSize
    +            && loopCounter < totalAttemptsToRemoveFromChannel) {
    +            loopCounter += 1
    +            Option(channel.take()) match {
    +              case Some(event) =>
    +                events.add(new SparkSinkEvent(toCharSequenceMap(event.getHeaders),
    +                  ByteBuffer.wrap(event.getBody)))
    +                gotEventsInThisTxn = true
    +              case None =>
    +                if (!gotEventsInThisTxn) {
    +                  TimeUnit.MILLISECONDS.sleep(500)
    +                } else {
    +                  loop.break()
    +                }
    +            }
    +          }
    +        }
    +        if (!gotEventsInThisTxn) {
    +          throw new FlumeException("Tried too many times, didn't get any events from the channel")
    +        }
    +        // At this point, the events are available, so fill them into the event batch
    +        eventBatch = new EventBatch(seqNum, events)
    +      })
    +    } catch {
    +      case e: Throwable =>
    --- End diff --
    
    Didn't know that. Will do sir


---
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 infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] spark pull request: SPARK-1729. Make Flume pull data from source, ...

Posted by tdas <gi...@git.apache.org>.
Github user tdas commented on a diff in the pull request:

    https://github.com/apache/spark/pull/807#discussion_r13463759
  
    --- Diff: external/flume-sink/src/main/avro/sparkflume.avdl ---
    @@ -0,0 +1,40 @@
    +/**
    + * 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.
    + */
    +
    +@namespace("org.apache.spark.flume")
    +
    +protocol SparkFlumeProtocol {
    +
    +  record SparkSinkEvent {
    +    map<string> headers;
    +    bytes body;
    +  }
    +
    +  record EventBatch {
    +    string sequenceNumber;
    +    array<SparkSinkEvent> eventBatch;
    --- End diff --
    
    nit: its becomes a little awkward to have a class `EventBatch` that has a field `eventBatch`. It would be "nicer" to call this field `events`.


---
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 infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] spark pull request: SPARK-1729. Make Flume pull data from source, ...

Posted by harishreedharan <gi...@git.apache.org>.
Github user harishreedharan commented on a diff in the pull request:

    https://github.com/apache/spark/pull/807#discussion_r13466337
  
    --- Diff: external/flume-sink/src/main/scala/org/apache/spark/flume/sink/SparkSink.scala ---
    @@ -0,0 +1,392 @@
    +/*
    + * 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.flume.sink
    +
    +import org.apache.flume.sink.AbstractSink
    +import java.util.concurrent.locks.ReentrantLock
    +import org.apache.flume.Sink.Status
    +import org.apache.spark.flume.{SparkSinkEvent, EventBatch, SparkFlumeProtocol}
    +import scala.util.control.Breaks
    +import java.nio.ByteBuffer
    +import org.apache.flume.{FlumeException, Context}
    +import org.slf4j.LoggerFactory
    +import java.util.concurrent.atomic.AtomicLong
    +import org.apache.commons.lang.RandomStringUtils
    +import java.util.concurrent._
    +import java.util
    +import org.apache.flume.conf.{ConfigurationException, Configurable}
    +import com.google.common.util.concurrent.ThreadFactoryBuilder
    +import org.apache.avro.ipc.NettyServer
    +import org.apache.avro.ipc.specific.SpecificResponder
    +import java.net.InetSocketAddress
    +
    +class SparkSink() extends AbstractSink with Configurable {
    +  private val LOG = LoggerFactory.getLogger(this.getClass)
    +  private val lock = new ReentrantLock()
    +  private val blockingCondition = lock.newCondition()
    +
    +  // This sink will not persist sequence numbers and reuses them if it gets restarted.
    +  // So it is possible to commit a transaction which may have been meant for the sink before the
    +  // restart.
    +  // Since the new txn may not have the same sequence number we must guard against accidentally
    +  // committing
    +  // a new transaction. To reduce the probability of that happening a random string is prepended
    +  // to the sequence number.
    +  // Does not change for life of sink
    +  private val seqBase = RandomStringUtils.randomAlphanumeric(8)
    +  // Incremented for each transaction
    +  private val seqNum = new AtomicLong(0)
    +
    +  private var transactionExecutorOpt: Option[ExecutorService] = None
    +
    +  private var numProcessors: Integer = SparkSinkConfig.DEFAULT_PROCESSOR_COUNT
    +  private var transactionTimeout = SparkSinkConfig.DEFAULT_TRANSACTION_TIMEOUT
    +
    +  private val processorMap = new ConcurrentHashMap[CharSequence, TransactionProcessor]()
    +
    +  private var processorFactory: Option[SparkHandlerFactory] = None
    +  private var hostname: String = SparkSinkConfig.DEFAULT_HOSTNAME
    +  private var port: Int = 0
    +  private var maxThreads: Int = SparkSinkConfig.DEFAULT_MAX_THREADS
    +  private var serverOpt: Option[NettyServer] = None
    +  private var running = false
    +
    +  override def start() {
    +    transactionExecutorOpt = Option(Executors.newFixedThreadPool(numProcessors,
    +      new ThreadFactoryBuilder().setDaemon(true)
    +        .setNameFormat("Spark Sink, " + getName + " Processor Thread - %d").build()))
    +
    +    processorFactory = Option(new SparkHandlerFactory(numProcessors))
    +
    +    val responder = new SpecificResponder(classOf[SparkFlumeProtocol], new AvroCallbackHandler())
    +
    +    // Using the constructor that takes specific thread-pools requires bringing in netty
    +    // dependencies which are being excluded in the build. In practice,
    +    // Netty dependencies are already available on the JVM as Flume would have pulled them in.
    +    serverOpt = Option(new NettyServer(responder, new InetSocketAddress(hostname, port)))
    +
    +    serverOpt.map(server => server.start())
    +    lock.lock()
    +    try {
    +      running = true
    +    } finally {
    +      lock.unlock()
    +    }
    +    super.start()
    +  }
    +
    +  override def stop() {
    +    transactionExecutorOpt.map(executor => executor.shutdownNow())
    +    serverOpt.map(server => {
    +      server.close()
    +      server.join()
    +    })
    +    lock.lock()
    +    try {
    +      running = false
    +      blockingCondition.signalAll()
    +    } finally {
    +      lock.unlock()
    +    }
    +  }
    +
    +  override def configure(ctx: Context) {
    +    import SparkSinkConfig._
    +    hostname = ctx.getString(CONF_HOSTNAME, DEFAULT_HOSTNAME)
    +    val portOpt = Option(ctx.getInteger(CONF_PORT))
    +    if(portOpt.isDefined) {
    +      port = portOpt.get
    +    } else {
    +      throw new ConfigurationException("The Port to bind must be specified")
    +    }
    +    numProcessors = ctx.getInteger(PROCESSOR_COUNT, DEFAULT_PROCESSOR_COUNT)
    +    transactionTimeout = ctx.getInteger(CONF_TRANSACTION_TIMEOUT, DEFAULT_TRANSACTION_TIMEOUT)
    +    maxThreads = ctx.getInteger(CONF_MAX_THREADS, DEFAULT_MAX_THREADS)
    +  }
    +
    +  override def process(): Status = {
    +    // This method is called in a loop by the Flume framework - block it until the sink is
    +    // stopped to save CPU resources
    +    lock.lock()
    +    try {
    +      while(running) {
    +        blockingCondition.await()
    +      }
    +    } finally {
    +      lock.unlock()
    +    }
    +    Status.BACKOFF
    +  }
    +
    +
    +  // Object representing an empty batch returned by the txn processor due to some error.
    +  case object ErrorEventBatch extends EventBatch
    +
    +  private class AvroCallbackHandler() extends SparkFlumeProtocol {
    +
    +    override def getEventBatch(n: Int): EventBatch = {
    +      val processor = processorFactory.get.checkOut(n)
    +      transactionExecutorOpt.map(executor => executor.submit(processor))
    +      // Wait until a batch is available - can be null if some error was thrown
    +      val eventBatch = processor.eventQueue.take()
    +      eventBatch match {
    +        case ErrorEventBatch => throw new FlumeException("Something went wrong. No events" +
    +          " retrieved from channel.")
    +        case events => {
    +          processorMap.put(events.getSequenceNumber, processor)
    +          if (LOG.isDebugEnabled) {
    +            LOG.debug("Sent " + events.getEventBatch.size() +
    +              " events with sequence number: " + events.getSequenceNumber)
    +          }
    +          events
    +        }
    +      }
    +    }
    +
    +    override def ack(sequenceNumber: CharSequence): Void = {
    +      completeTransaction(sequenceNumber, success = true)
    +      null
    +    }
    +
    +    override def nack(sequenceNumber: CharSequence): Void = {
    +      completeTransaction(sequenceNumber, success = false)
    +      LOG.info("Spark failed to commit transaction. Will reattempt events.")
    +      null
    +    }
    +
    +    def completeTransaction(sequenceNumber: CharSequence, success: Boolean) {
    +      val processorOpt = Option(processorMap.remove(sequenceNumber))
    +      if (processorOpt.isDefined) {
    +        val processor = processorOpt.get
    +        processor.resultQueueUpdateLock.lock()
    +        try {
    +          // Is the sequence number the same as the one the processor is processing? If not,
    +          // don't update {
    +          if (processor.eventBatch.getSequenceNumber.equals(sequenceNumber)) {
    +            processor.resultQueue.put(success)
    +          }
    +        } finally {
    +          processor.resultQueueUpdateLock.unlock()
    +        }
    +      }
    +    }
    +  }
    +
    +  // Flume forces transactions to be thread-local (horrible, I know!)
    +  // So the sink basically spawns a new thread to pull the events out within a transaction.
    +  // The thread fills in the event batch object that is set before the thread is scheduled.
    +  // After filling it in, the thread waits on a condition - which is released only
    +  // when the success message comes back for the specific sequence number for that event batch.
    +  /**
    +   * This class represents a transaction on the Flume channel. This class runs a separate thread
    +   * which owns the transaction. It is blocked until the success call for that transaction comes
    +   * back.
    +   * @param maxBatchSize
    +   */
    +  private class TransactionProcessor(var maxBatchSize: Int) extends Callable[Void] {
    +    // Must be set to a new event batch before scheduling this!!
    +    val eventBatch = new EventBatch("", new util.LinkedList[SparkSinkEvent])
    +    val eventQueue = new SynchronousQueue[EventBatch]()
    +    val resultQueue = new SynchronousQueue[Boolean]()
    +    val resultQueueUpdateLock = new ReentrantLock()
    +
    +    object Zero {
    +      val zero = "0" // Oh, I miss static finals
    +    }
    +
    +
    +    override def call(): Void = {
    +      val tx = getChannel.getTransaction
    +      tx.begin()
    +      try {
    +        eventBatch.setSequenceNumber(seqBase + seqNum.incrementAndGet())
    +        val events = eventBatch.getEventBatch
    +        events.clear()
    +        val loop = new Breaks
    +        var gotEventsInThisTxn = false
    +        loop.breakable {
    +          var i = 0
    +          // Using for here causes the maxBatchSize change to be ineffective as the Range gets
    +          // pregenerated
    +          while (i < maxBatchSize) {
    +            i += 1
    +            val eventOpt = Option(getChannel.take())
    +            eventOpt.map(event => {
    +              events.add(new SparkSinkEvent(toCharSequenceMap(event
    +                .getHeaders),
    +                ByteBuffer.wrap(event.getBody)))
    +              gotEventsInThisTxn = true
    +            })
    +            if (eventOpt.isEmpty) {
    +              if (!gotEventsInThisTxn) {
    +                // To avoid sending empty batches, we wait till events are available backing off
    +                // between attempts to get events. Each attempt to get an event though causes one
    +                // iteration to be lost. To ensure that we still send back maxBatchSize number of
    +                // events, we cheat and increase the maxBatchSize by 1 to account for the lost
    +                // iteration. Even throwing an exception is expensive as Avro will serialize it
    +                // and send it over the wire, which is useless. Before incrementing though,
    +                // ensure that we are not anywhere near INT_MAX.
    +                if (maxBatchSize >= Int.MaxValue / 2) {
    --- End diff --
    
    It is too expensive to send empty batches, so we will keep polling the channel to see if events are available. Each time we poll, it means that we need to increase the maxBatchSize by 1. I realize it is counter-intuitive now that I read the code myself. I will use two variables so it is clearer.


---
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 infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] spark pull request: SPARK-1729. Make Flume pull data from source, ...

Posted by harishreedharan <gi...@git.apache.org>.
Github user harishreedharan commented on a diff in the pull request:

    https://github.com/apache/spark/pull/807#discussion_r12802646
  
    --- Diff: external/flume-sink/src/main/scala/org/apache/spark/flume/sink/SparkSink.scala ---
    @@ -0,0 +1,392 @@
    +/*
    + * 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.flume.sink
    +
    +import org.apache.flume.sink.AbstractSink
    --- End diff --
    
    scalastyle did not seem to complain, so I left in the order Intellij pulled them in. Is there a style we use for this? I can sort it in the next iteration, once some more code comments come in.


---
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 infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] spark pull request: SPARK-1729. Make Flume pull data from source, ...

Posted by SparkQA <gi...@git.apache.org>.
Github user SparkQA commented on the pull request:

    https://github.com/apache/spark/pull/807#issuecomment-49673605
  
    QA results for PR 807:<br>- This patch FAILED unit tests.<br>- This patch merges cleanly<br>- This patch adds the following public classes (experimental):<br>class SparkSink extends AbstractSink with Logging with Configurable {<br>class FlumePollingInputDStream[T: ClassTag](<br>class FlumePollingReceiver(<br>class SparkFlumePollingEvent extends Externalizable with Logging {<br><br>For more information see test ouptut:<br>https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/16932/consoleFull


---
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 infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] spark pull request: SPARK-1729. Make Flume pull data from source, ...

Posted by tdas <gi...@git.apache.org>.
Github user tdas commented on a diff in the pull request:

    https://github.com/apache/spark/pull/807#discussion_r13833797
  
    --- Diff: external/flume-sink/src/main/scala/org/apache/spark/flume/sink/SparkSink.scala ---
    @@ -0,0 +1,432 @@
    +/*
    + * 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.flume.sink
    +
    +import java.net.InetSocketAddress
    +import java.nio.ByteBuffer
    +import java.util
    +import java.util.concurrent._
    +import java.util.concurrent.atomic.AtomicLong
    +
    +import scala.util.control.Breaks
    +
    +import com.google.common.util.concurrent.ThreadFactoryBuilder
    +import org.apache.avro.ipc.NettyServer
    +import org.apache.avro.ipc.specific.SpecificResponder
    +import org.apache.commons.lang.RandomStringUtils
    +import org.apache.flume.Sink.Status
    +import org.apache.flume.conf.{ConfigurationException, Configurable}
    +import org.apache.flume.sink.AbstractSink
    +import org.apache.flume.{Channel, Transaction, FlumeException, Context}
    +import org.slf4j.LoggerFactory
    +
    +import org.apache.spark.flume.{SparkSinkEvent, EventBatch, SparkFlumeProtocol}
    +
    +/**
    + * A sink that uses Avro RPC to run a server that can be polled by Spark's
    + * FlumePollingInputDStream. This sink has the following configuration parameters:
    + *
    + * hostname - The hostname to bind to. Default: 0.0.0.0
    + * port - The port to bind to. (No default - mandatory)
    + * timeout - Time in seconds after which a transaction is rolled back,
    + * if an ACK is not received from Spark within that time
    + * threads - Number of threads to use to receive requests from Spark (Default: 10)
    + *
    + */
    +// Flume forces transactions to be thread-local. So each transaction *must* be committed, or
    +// rolled back from the thread it was originally created in. So each getEvents call from Spark
    +// creates a TransactionProcessor which runs in a new thread, in which the transaction is created
    +// and events are pulled off the channel. Once the events are sent to spark,
    +// that thread is blocked and the TransactionProcessor is saved in a map,
    +// until an ACK or NACK comes back or the transaction times out (after the specified timeout).
    +// When the response comes, the TransactionProcessor is retrieved and then unblocked,
    +// at which point the transaction is committed or rolled back.
    +class SparkSink extends AbstractSink with Configurable {
    +
    +  // Size of the pool to use for holding transaction processors.
    +  private var poolSize: Integer = SparkSinkConfig.DEFAULT_THREADS
    +
    +  // Timeout for each transaction. If spark does not respond in this much time,
    +  // rollback the transaction
    +  private var transactionTimeout = SparkSinkConfig.DEFAULT_TRANSACTION_TIMEOUT
    +
    +  // Address info to bind on
    +  private var hostname: String = SparkSinkConfig.DEFAULT_HOSTNAME
    +  private var port: Int = 0
    +
    +  // Handle to the server
    +  private var serverOpt: Option[NettyServer] = None
    +
    +  // The handler that handles the callback from Avro
    +  private var handler: Option[SparkAvroCallbackHandler] = None
    +
    +  // Latch that blocks off the Flume framework from wasting 1 thread.
    +  private val blockingLatch = new CountDownLatch(1)
    +
    +  override def start() {
    +    handler = Option(new SparkAvroCallbackHandler(poolSize, getChannel, transactionTimeout))
    +    val responder = new SpecificResponder(classOf[SparkFlumeProtocol], handler.get)
    +    // Using the constructor that takes specific thread-pools requires bringing in netty
    +    // dependencies which are being excluded in the build. In practice,
    +    // Netty dependencies are already available on the JVM as Flume would have pulled them in.
    +    serverOpt = Option(new NettyServer(responder, new InetSocketAddress(hostname, port)))
    +    serverOpt.map(server => {
    +      server.start()
    +    })
    +    super.start()
    +  }
    +
    +  override def stop() {
    +    handler.map(callbackHandler => {
    +      callbackHandler.shutdown()
    +    })
    +    serverOpt.map(server => {
    +      server.close()
    +      server.join()
    +    })
    +    blockingLatch.countDown()
    +    super.stop()
    +  }
    +
    +  /**
    +   * @param ctx
    +   */
    +  override def configure(ctx: Context) {
    +    import SparkSinkConfig._
    +    hostname = ctx.getString(CONF_HOSTNAME, DEFAULT_HOSTNAME)
    +    port = Option(ctx.getInteger(CONF_PORT)).
    +      getOrElse(throw new ConfigurationException("The port to bind to must be specified"))
    +    poolSize = ctx.getInteger(THREADS, DEFAULT_THREADS)
    +    transactionTimeout = ctx.getInteger(CONF_TRANSACTION_TIMEOUT, DEFAULT_TRANSACTION_TIMEOUT)
    +  }
    +
    +  override def process(): Status = {
    +    // This method is called in a loop by the Flume framework - block it until the sink is
    +    // stopped to save CPU resources. The sink runner will interrupt this thread when the sink is
    +    // being shut down.
    +    blockingLatch.await()
    +    Status.BACKOFF
    +  }
    +}
    +
    +/**
    + * Class that implements the SparkFlumeProtocol, that is used by the Avro Netty Server to process
    + * requests. Each getEvents, ack and nack call is forwarded to an instance of this class.
    + * @param threads Number of threads to use to process requests.
    + * @param channel The channel that the sink pulls events from
    + * @param transactionTimeout Timeout in millis after which the transaction if not acked by Spark
    + *                           is rolled back.
    + */
    +private class SparkAvroCallbackHandler(val threads: Int, val channel: Channel,
    +  val transactionTimeout: Int) extends SparkFlumeProtocol {
    +  private val LOG = LoggerFactory.getLogger(classOf[SparkAvroCallbackHandler])
    +  val transactionExecutorOpt = Option(Executors.newFixedThreadPool(threads,
    +    new ThreadFactoryBuilder().setDaemon(true)
    +      .setNameFormat("Spark Sink Processor Thread - %d").build()))
    +  private val processorMap = new ConcurrentHashMap[CharSequence, TransactionProcessor]()
    +  // This sink will not persist sequence numbers and reuses them if it gets restarted.
    +  // So it is possible to commit a transaction which may have been meant for the sink before the
    +  // restart.
    +  // Since the new txn may not have the same sequence number we must guard against accidentally
    +  // committing a new transaction. To reduce the probability of that happening a random string is
    +  // prepended to the sequence number. Does not change for life of sink
    +  private val seqBase = RandomStringUtils.randomAlphanumeric(8)
    +  private val seqCounter = new AtomicLong(0)
    +
    +  /**
    +   * Returns a bunch of events to Spark over Avro RPC.
    +   * @param n Maximum number of events to return in a batch
    +   * @return [[EventBatch]] instance that has a sequence number and an array of at most n events
    +   */
    +  override def getEventBatch(n: Int): EventBatch = {
    +    val sequenceNumber = seqBase + seqCounter.incrementAndGet()
    +    val processor = new TransactionProcessor(channel, sequenceNumber,
    +      n, transactionTimeout, this)
    +    transactionExecutorOpt.map(executor => {
    +      executor.submit(processor)
    +    })
    +    // Wait until a batch is available - can be null if some error was thrown
    +    processor.getEventBatch match {
    +      case ErrorEventBatch => throw new FlumeException("Something went wrong. No events" +
    +        " retrieved from channel.")
    +      case eventBatch: EventBatch =>
    +        processorMap.put(sequenceNumber, processor)
    +        if (LOG.isDebugEnabled()) {
    +          LOG.debug("Sent " + eventBatch.getEvents.size() +
    +            " events with sequence number: " + eventBatch.getSequenceNumber)
    +        }
    +        eventBatch
    +    }
    +  }
    +
    +  /**
    +   * Called by Spark to indicate successful commit of a batch
    +   * @param sequenceNumber The sequence number of the event batch that was successful
    +   */
    +  override def ack(sequenceNumber: CharSequence): Void = {
    +    completeTransaction(sequenceNumber, success = true)
    +    null
    +  }
    +
    +  /**
    +   * Called by Spark to indicate failed commit of a batch
    +   * @param sequenceNumber The sequence number of the event batch that failed
    +   * @return
    +   */
    +  override def nack(sequenceNumber: CharSequence): Void = {
    +    completeTransaction(sequenceNumber, success = false)
    +    LOG.info("Spark failed to commit transaction. Will reattempt events.")
    +    null
    +  }
    +
    +  /**
    +   * Helper method to commit or rollback a transaction.
    +   * @param sequenceNumber The sequence number of the batch that was completed
    +   * @param success Whether the batch was successful or not.
    +   */
    +  private def completeTransaction(sequenceNumber: CharSequence, success: Boolean) {
    +    Option(removeAndGetProcessor(sequenceNumber)).map(processor => {
    +      processor.batchProcessed(success)
    +    })
    +  }
    +
    +  /**
    +   * Helper method to remove the TxnProcessor for a Sequence Number. Can be used to avoid a leak.
    +   * @param sequenceNumber
    +   * @return The transaction processor for the corresponding batch. Note that this instance is no
    +   *         longer tracked and the caller is responsible for that txn processor.
    +   */
    +  private[flume] def removeAndGetProcessor(sequenceNumber: CharSequence): TransactionProcessor = {
    +    processorMap.remove(sequenceNumber.toString) // The toString is required!
    +  }
    +
    +  /**
    +   * Shuts down the executor used to process transactions.
    +   */
    +  def shutdown() {
    +    transactionExecutorOpt.map(executor => {
    +      executor.shutdownNow()
    +    })
    +  }
    +}
    +
    +/**
    + * Object representing an empty batch returned by the txn processor due to some error.
    + */
    +case object ErrorEventBatch extends EventBatch
    --- End diff --
    
    Do we need a ErrorEventBatch? The `getEventBatch` can simply return an `Option[EventBatch]` to signify whether the batch was successfully got or not. The only reason I see that there is a reason for ErrorEventBatch is if you want to pass on extra error info about it, which is not the case here.


---
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 infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] spark pull request: SPARK-1729. Make Flume pull data from source, ...

Posted by harishreedharan <gi...@git.apache.org>.
Github user harishreedharan commented on a diff in the pull request:

    https://github.com/apache/spark/pull/807#discussion_r12802607
  
    --- Diff: external/flume-sink/pom.xml ---
    @@ -0,0 +1,82 @@
    +<?xml version="1.0" encoding="UTF-8"?>
    --- End diff --
    
    The sink will be deployed to a Flume agent and not within the spark application. Adding it in external/flume would require that all of the spark dependencies be bundled with the jar, while keeping this module separate (which does not depend on the rest of Spark) allows the user to simply deploy this jar to the Flume plugins directory. In fact, this module does not have any dependencies that Flume already does not pull in by default.


---
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 infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] spark pull request: SPARK-1729. Make Flume pull data from source, ...

Posted by srowen <gi...@git.apache.org>.
Github user srowen commented on a diff in the pull request:

    https://github.com/apache/spark/pull/807#discussion_r12781207
  
    --- Diff: external/flume-sink/src/main/scala/org/apache/spark/flume/sink/SparkSink.scala ---
    @@ -0,0 +1,392 @@
    +/*
    + * 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.flume.sink
    +
    +import org.apache.flume.sink.AbstractSink
    --- End diff --
    
    Sort these imports?


---
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 infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] spark pull request: SPARK-1729. Make Flume pull data from source, ...

Posted by tdas <gi...@git.apache.org>.
Github user tdas commented on a diff in the pull request:

    https://github.com/apache/spark/pull/807#discussion_r13838518
  
    --- Diff: external/flume-sink/src/main/scala/org/apache/spark/flume/sink/SparkSink.scala ---
    @@ -0,0 +1,432 @@
    +/*
    + * 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.flume.sink
    +
    +import java.net.InetSocketAddress
    +import java.nio.ByteBuffer
    +import java.util
    +import java.util.concurrent._
    +import java.util.concurrent.atomic.AtomicLong
    +
    +import scala.util.control.Breaks
    +
    +import com.google.common.util.concurrent.ThreadFactoryBuilder
    +import org.apache.avro.ipc.NettyServer
    +import org.apache.avro.ipc.specific.SpecificResponder
    +import org.apache.commons.lang.RandomStringUtils
    +import org.apache.flume.Sink.Status
    +import org.apache.flume.conf.{ConfigurationException, Configurable}
    +import org.apache.flume.sink.AbstractSink
    +import org.apache.flume.{Channel, Transaction, FlumeException, Context}
    +import org.slf4j.LoggerFactory
    +
    +import org.apache.spark.flume.{SparkSinkEvent, EventBatch, SparkFlumeProtocol}
    +
    +/**
    + * A sink that uses Avro RPC to run a server that can be polled by Spark's
    + * FlumePollingInputDStream. This sink has the following configuration parameters:
    + *
    + * hostname - The hostname to bind to. Default: 0.0.0.0
    + * port - The port to bind to. (No default - mandatory)
    + * timeout - Time in seconds after which a transaction is rolled back,
    + * if an ACK is not received from Spark within that time
    + * threads - Number of threads to use to receive requests from Spark (Default: 10)
    + *
    + */
    +// Flume forces transactions to be thread-local. So each transaction *must* be committed, or
    +// rolled back from the thread it was originally created in. So each getEvents call from Spark
    +// creates a TransactionProcessor which runs in a new thread, in which the transaction is created
    +// and events are pulled off the channel. Once the events are sent to spark,
    +// that thread is blocked and the TransactionProcessor is saved in a map,
    +// until an ACK or NACK comes back or the transaction times out (after the specified timeout).
    +// When the response comes, the TransactionProcessor is retrieved and then unblocked,
    +// at which point the transaction is committed or rolled back.
    +class SparkSink extends AbstractSink with Configurable {
    +
    +  // Size of the pool to use for holding transaction processors.
    +  private var poolSize: Integer = SparkSinkConfig.DEFAULT_THREADS
    +
    +  // Timeout for each transaction. If spark does not respond in this much time,
    +  // rollback the transaction
    +  private var transactionTimeout = SparkSinkConfig.DEFAULT_TRANSACTION_TIMEOUT
    +
    +  // Address info to bind on
    +  private var hostname: String = SparkSinkConfig.DEFAULT_HOSTNAME
    +  private var port: Int = 0
    +
    +  // Handle to the server
    +  private var serverOpt: Option[NettyServer] = None
    +
    +  // The handler that handles the callback from Avro
    +  private var handler: Option[SparkAvroCallbackHandler] = None
    +
    +  // Latch that blocks off the Flume framework from wasting 1 thread.
    +  private val blockingLatch = new CountDownLatch(1)
    +
    +  override def start() {
    +    handler = Option(new SparkAvroCallbackHandler(poolSize, getChannel, transactionTimeout))
    +    val responder = new SpecificResponder(classOf[SparkFlumeProtocol], handler.get)
    +    // Using the constructor that takes specific thread-pools requires bringing in netty
    +    // dependencies which are being excluded in the build. In practice,
    +    // Netty dependencies are already available on the JVM as Flume would have pulled them in.
    +    serverOpt = Option(new NettyServer(responder, new InetSocketAddress(hostname, port)))
    +    serverOpt.map(server => {
    +      server.start()
    +    })
    +    super.start()
    +  }
    +
    +  override def stop() {
    +    handler.map(callbackHandler => {
    +      callbackHandler.shutdown()
    +    })
    +    serverOpt.map(server => {
    +      server.close()
    +      server.join()
    +    })
    +    blockingLatch.countDown()
    +    super.stop()
    +  }
    +
    +  /**
    +   * @param ctx
    +   */
    +  override def configure(ctx: Context) {
    +    import SparkSinkConfig._
    +    hostname = ctx.getString(CONF_HOSTNAME, DEFAULT_HOSTNAME)
    +    port = Option(ctx.getInteger(CONF_PORT)).
    +      getOrElse(throw new ConfigurationException("The port to bind to must be specified"))
    +    poolSize = ctx.getInteger(THREADS, DEFAULT_THREADS)
    +    transactionTimeout = ctx.getInteger(CONF_TRANSACTION_TIMEOUT, DEFAULT_TRANSACTION_TIMEOUT)
    +  }
    +
    +  override def process(): Status = {
    +    // This method is called in a loop by the Flume framework - block it until the sink is
    +    // stopped to save CPU resources. The sink runner will interrupt this thread when the sink is
    +    // being shut down.
    +    blockingLatch.await()
    +    Status.BACKOFF
    +  }
    +}
    +
    +/**
    + * Class that implements the SparkFlumeProtocol, that is used by the Avro Netty Server to process
    + * requests. Each getEvents, ack and nack call is forwarded to an instance of this class.
    + * @param threads Number of threads to use to process requests.
    + * @param channel The channel that the sink pulls events from
    + * @param transactionTimeout Timeout in millis after which the transaction if not acked by Spark
    + *                           is rolled back.
    + */
    +private class SparkAvroCallbackHandler(val threads: Int, val channel: Channel,
    +  val transactionTimeout: Int) extends SparkFlumeProtocol {
    +  private val LOG = LoggerFactory.getLogger(classOf[SparkAvroCallbackHandler])
    +  val transactionExecutorOpt = Option(Executors.newFixedThreadPool(threads,
    +    new ThreadFactoryBuilder().setDaemon(true)
    +      .setNameFormat("Spark Sink Processor Thread - %d").build()))
    +  private val processorMap = new ConcurrentHashMap[CharSequence, TransactionProcessor]()
    +  // This sink will not persist sequence numbers and reuses them if it gets restarted.
    +  // So it is possible to commit a transaction which may have been meant for the sink before the
    +  // restart.
    +  // Since the new txn may not have the same sequence number we must guard against accidentally
    +  // committing a new transaction. To reduce the probability of that happening a random string is
    +  // prepended to the sequence number. Does not change for life of sink
    +  private val seqBase = RandomStringUtils.randomAlphanumeric(8)
    +  private val seqCounter = new AtomicLong(0)
    +
    +  /**
    +   * Returns a bunch of events to Spark over Avro RPC.
    +   * @param n Maximum number of events to return in a batch
    +   * @return [[EventBatch]] instance that has a sequence number and an array of at most n events
    +   */
    +  override def getEventBatch(n: Int): EventBatch = {
    +    val sequenceNumber = seqBase + seqCounter.incrementAndGet()
    +    val processor = new TransactionProcessor(channel, sequenceNumber,
    +      n, transactionTimeout, this)
    +    transactionExecutorOpt.map(executor => {
    +      executor.submit(processor)
    +    })
    +    // Wait until a batch is available - can be null if some error was thrown
    +    processor.getEventBatch match {
    +      case ErrorEventBatch => throw new FlumeException("Something went wrong. No events" +
    +        " retrieved from channel.")
    +      case eventBatch: EventBatch =>
    +        processorMap.put(sequenceNumber, processor)
    +        if (LOG.isDebugEnabled()) {
    +          LOG.debug("Sent " + eventBatch.getEvents.size() +
    +            " events with sequence number: " + eventBatch.getSequenceNumber)
    +        }
    +        eventBatch
    +    }
    +  }
    +
    +  /**
    +   * Called by Spark to indicate successful commit of a batch
    +   * @param sequenceNumber The sequence number of the event batch that was successful
    +   */
    +  override def ack(sequenceNumber: CharSequence): Void = {
    +    completeTransaction(sequenceNumber, success = true)
    +    null
    +  }
    +
    +  /**
    +   * Called by Spark to indicate failed commit of a batch
    +   * @param sequenceNumber The sequence number of the event batch that failed
    +   * @return
    +   */
    +  override def nack(sequenceNumber: CharSequence): Void = {
    +    completeTransaction(sequenceNumber, success = false)
    +    LOG.info("Spark failed to commit transaction. Will reattempt events.")
    +    null
    +  }
    +
    +  /**
    +   * Helper method to commit or rollback a transaction.
    +   * @param sequenceNumber The sequence number of the batch that was completed
    +   * @param success Whether the batch was successful or not.
    +   */
    +  private def completeTransaction(sequenceNumber: CharSequence, success: Boolean) {
    +    Option(removeAndGetProcessor(sequenceNumber)).map(processor => {
    +      processor.batchProcessed(success)
    +    })
    +  }
    +
    +  /**
    +   * Helper method to remove the TxnProcessor for a Sequence Number. Can be used to avoid a leak.
    +   * @param sequenceNumber
    +   * @return The transaction processor for the corresponding batch. Note that this instance is no
    +   *         longer tracked and the caller is responsible for that txn processor.
    +   */
    +  private[flume] def removeAndGetProcessor(sequenceNumber: CharSequence): TransactionProcessor = {
    +    processorMap.remove(sequenceNumber.toString) // The toString is required!
    +  }
    +
    +  /**
    +   * Shuts down the executor used to process transactions.
    +   */
    +  def shutdown() {
    +    transactionExecutorOpt.map(executor => {
    +      executor.shutdownNow()
    +    })
    +  }
    +}
    +
    +/**
    + * Object representing an empty batch returned by the txn processor due to some error.
    + */
    +case object ErrorEventBatch extends EventBatch
    +
    +// Flume forces transactions to be thread-local (horrible, I know!)
    +// So the sink basically spawns a new thread to pull the events out within a transaction.
    +// The thread fills in the event batch object that is set before the thread is scheduled.
    +// After filling it in, the thread waits on a condition - which is released only
    +// when the success message comes back for the specific sequence number for that event batch.
    +/**
    + * This class represents a transaction on the Flume channel. This class runs a separate thread
    + * which owns the transaction. The thread is blocked until the success call for that transaction
    + * comes back with an ACK or NACK.
    + * @param channel The channel from which to pull events
    + * @param seqNum The sequence number to use for the transaction. Must be unique
    + * @param maxBatchSize The maximum number of events to process per batch
    + * @param transactionTimeout Time in seconds after which a transaction must be rolled back
    + *                           without waiting for an ACK from Spark
    + * @param parent The parent [[SparkAvroCallbackHandler]] instance, for reporting timeouts
    + */
    +private class TransactionProcessor(val channel: Channel, val seqNum: String,
    +  var maxBatchSize: Int, val transactionTimeout: Int,
    +  val parent: SparkAvroCallbackHandler) extends Callable[Void] {
    +
    +  private val LOG = LoggerFactory.getLogger(classOf[TransactionProcessor])
    +
    +  // If a real batch is not returned, we always have to return an error batch.
    +  @volatile private var eventBatch: EventBatch = ErrorEventBatch
    +
    +  // Synchronization primitives
    +  val batchGeneratedLatch = new CountDownLatch(1)
    +  val batchAckLatch = new CountDownLatch(1)
    +
    +  // Sanity check to ensure we don't loop like crazy
    +  val totalAttemptsToRemoveFromChannel = Int.MaxValue / 2
    +
    +  // OK to use volatile, since the change would only make this true (otherwise it will be
    +  // changed to false - we never apply a negation operation to this) - which means the transaction
    +  // succeeded.
    +  @volatile private var batchSuccess = false
    +
    +  // The transaction that this processor would handle
    +  var txOpt: Option[Transaction] = None
    +
    +  /**
    +   * Get an event batch from the channel. This method will block until a batch of events is
    +   * available from the channel. If no events are available after a large number of attempts of
    +   * polling the channel, this method will return [[ErrorEventBatch]].
    +   *
    +   * @return An [[EventBatch]] instance with sequence number set to [[seqNum]], filled with a
    +   *         maximum of [[maxBatchSize]] events
    +   */
    +  def getEventBatch: EventBatch = {
    +    batchGeneratedLatch.await()
    +    eventBatch
    +  }
    +
    +  /**
    +   * This method is to be called by the sink when it receives an ACK or NACK from Spark. This
    +   * method is a no-op if it is called after [[transactionTimeout]] has expired since
    +   * [[getEventBatch]] returned a batch of events.
    +   * @param success True if an ACK was received and the transaction should be committed, else false.
    +   */
    +  def batchProcessed(success: Boolean) {
    +    if (LOG.isDebugEnabled) {
    +      LOG.debug("Batch processed for sequence number: " + seqNum)
    +    }
    +    batchSuccess = success
    +    batchAckLatch.countDown()
    +  }
    +
    +  /**
    +   * Populates events into the event batch. If the batch cannot be populated,
    +   * this method will not set the event batch which will stay [[ErrorEventBatch]]
    +   */
    +  private def populateEvents() {
    +    try {
    +      txOpt = Option(channel.getTransaction)
    +      txOpt.map(tx => {
    +        tx.begin()
    +        val events = new util.ArrayList[SparkSinkEvent](maxBatchSize)
    +        val loop = new Breaks
    +        var gotEventsInThisTxn = false
    +        var loopCounter: Int = 0
    +        loop.breakable {
    +          while (events.size() < maxBatchSize
    +            && loopCounter < totalAttemptsToRemoveFromChannel) {
    +            loopCounter += 1
    +            Option(channel.take()) match {
    +              case Some(event) =>
    +                events.add(new SparkSinkEvent(toCharSequenceMap(event.getHeaders),
    +                  ByteBuffer.wrap(event.getBody)))
    +                gotEventsInThisTxn = true
    +              case None =>
    +                if (!gotEventsInThisTxn) {
    +                  TimeUnit.MILLISECONDS.sleep(500)
    +                } else {
    +                  loop.break()
    +                }
    +            }
    +          }
    +        }
    +        if (!gotEventsInThisTxn) {
    +          throw new FlumeException("Tried too many times, didn't get any events from the channel")
    +        }
    +        // At this point, the events are available, so fill them into the event batch
    +        eventBatch = new EventBatch(seqNum, events)
    +      })
    +    } catch {
    +      case e: Throwable =>
    +        LOG.error("Error while processing transaction.", e)
    +        try {
    +          txOpt.map(tx => {
    +            rollbackAndClose(tx, close = true)
    +          })
    +        } finally {
    +          // Avro might serialize the exception and cause a NACK,
    +          // so don't bother with the transaction
    +          txOpt = None
    +        }
    +    } finally {
    +      batchGeneratedLatch.countDown()
    +    }
    +  }
    +
    +  /**
    +   * Waits for upto [[transactionTimeout]] seconds for an ACK. If an ACK comes in,
    +   * this method commits the transaction with the channel. If the ACK does not come in within
    +   * that time or a NACK comes in, this method rolls back the transaction.
    +   */
    +  private def processAckOrNack() {
    +    batchAckLatch.await(transactionTimeout, TimeUnit.SECONDS)
    +    txOpt.map(tx => {
    +      if (batchSuccess) {
    +        try {
    +          tx.commit()
    +        } catch {
    +          case e: Throwable =>
    +            rollbackAndClose(tx, close = false) // tx will be closed later anyway
    +        } finally {
    +          tx.close()
    +        }
    +      } else {
    +        rollbackAndClose(tx, close = true)
    +        // This might have been due to timeout or a NACK. Either way the following call does not
    +        // cause issues. This is required to ensure the TransactionProcessor instance is not leaked
    +        parent.removeAndGetProcessor(seqNum)
    +      }
    +    })
    +  }
    +
    +  /**
    +   * Helper method to rollback and optionally close a transaction
    +   * @param tx The transaction to rollback
    +   * @param close Whether the transaction should be closed or not after rolling back
    +   */
    +  private def rollbackAndClose(tx: Transaction, close: Boolean) {
    +    try {
    +      tx.rollback()
    +      LOG.warn("Spark was unable to successfully process the events. Transaction is being " +
    +        "rolled back.")
    +    } catch {
    +      case e: Throwable =>
    +        LOG.error("Error rolling back transaction. Rollback may have failed!", e)
    --- End diff --
    
    Same here, dont catch throwable, only exception


---
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 infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] spark pull request: SPARK-1729. Make Flume pull data from source, ...

Posted by tdas <gi...@git.apache.org>.
Github user tdas commented on a diff in the pull request:

    https://github.com/apache/spark/pull/807#discussion_r13838902
  
    --- Diff: external/flume-sink/src/main/scala/org/apache/spark/flume/sink/SparkSink.scala ---
    @@ -0,0 +1,432 @@
    +/*
    + * 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.flume.sink
    +
    +import java.net.InetSocketAddress
    +import java.nio.ByteBuffer
    +import java.util
    +import java.util.concurrent._
    +import java.util.concurrent.atomic.AtomicLong
    +
    +import scala.util.control.Breaks
    +
    +import com.google.common.util.concurrent.ThreadFactoryBuilder
    +import org.apache.avro.ipc.NettyServer
    +import org.apache.avro.ipc.specific.SpecificResponder
    +import org.apache.commons.lang.RandomStringUtils
    +import org.apache.flume.Sink.Status
    +import org.apache.flume.conf.{ConfigurationException, Configurable}
    +import org.apache.flume.sink.AbstractSink
    +import org.apache.flume.{Channel, Transaction, FlumeException, Context}
    +import org.slf4j.LoggerFactory
    +
    +import org.apache.spark.flume.{SparkSinkEvent, EventBatch, SparkFlumeProtocol}
    +
    +/**
    + * A sink that uses Avro RPC to run a server that can be polled by Spark's
    + * FlumePollingInputDStream. This sink has the following configuration parameters:
    + *
    + * hostname - The hostname to bind to. Default: 0.0.0.0
    + * port - The port to bind to. (No default - mandatory)
    + * timeout - Time in seconds after which a transaction is rolled back,
    + * if an ACK is not received from Spark within that time
    + * threads - Number of threads to use to receive requests from Spark (Default: 10)
    + *
    + */
    +// Flume forces transactions to be thread-local. So each transaction *must* be committed, or
    +// rolled back from the thread it was originally created in. So each getEvents call from Spark
    +// creates a TransactionProcessor which runs in a new thread, in which the transaction is created
    +// and events are pulled off the channel. Once the events are sent to spark,
    +// that thread is blocked and the TransactionProcessor is saved in a map,
    +// until an ACK or NACK comes back or the transaction times out (after the specified timeout).
    +// When the response comes, the TransactionProcessor is retrieved and then unblocked,
    +// at which point the transaction is committed or rolled back.
    +class SparkSink extends AbstractSink with Configurable {
    +
    +  // Size of the pool to use for holding transaction processors.
    +  private var poolSize: Integer = SparkSinkConfig.DEFAULT_THREADS
    +
    +  // Timeout for each transaction. If spark does not respond in this much time,
    +  // rollback the transaction
    +  private var transactionTimeout = SparkSinkConfig.DEFAULT_TRANSACTION_TIMEOUT
    +
    +  // Address info to bind on
    +  private var hostname: String = SparkSinkConfig.DEFAULT_HOSTNAME
    +  private var port: Int = 0
    +
    +  // Handle to the server
    +  private var serverOpt: Option[NettyServer] = None
    +
    +  // The handler that handles the callback from Avro
    +  private var handler: Option[SparkAvroCallbackHandler] = None
    +
    +  // Latch that blocks off the Flume framework from wasting 1 thread.
    +  private val blockingLatch = new CountDownLatch(1)
    +
    +  override def start() {
    +    handler = Option(new SparkAvroCallbackHandler(poolSize, getChannel, transactionTimeout))
    +    val responder = new SpecificResponder(classOf[SparkFlumeProtocol], handler.get)
    +    // Using the constructor that takes specific thread-pools requires bringing in netty
    +    // dependencies which are being excluded in the build. In practice,
    +    // Netty dependencies are already available on the JVM as Flume would have pulled them in.
    +    serverOpt = Option(new NettyServer(responder, new InetSocketAddress(hostname, port)))
    +    serverOpt.map(server => {
    +      server.start()
    +    })
    +    super.start()
    +  }
    +
    +  override def stop() {
    +    handler.map(callbackHandler => {
    +      callbackHandler.shutdown()
    +    })
    +    serverOpt.map(server => {
    +      server.close()
    +      server.join()
    +    })
    +    blockingLatch.countDown()
    +    super.stop()
    +  }
    +
    +  /**
    +   * @param ctx
    +   */
    +  override def configure(ctx: Context) {
    +    import SparkSinkConfig._
    +    hostname = ctx.getString(CONF_HOSTNAME, DEFAULT_HOSTNAME)
    +    port = Option(ctx.getInteger(CONF_PORT)).
    +      getOrElse(throw new ConfigurationException("The port to bind to must be specified"))
    +    poolSize = ctx.getInteger(THREADS, DEFAULT_THREADS)
    +    transactionTimeout = ctx.getInteger(CONF_TRANSACTION_TIMEOUT, DEFAULT_TRANSACTION_TIMEOUT)
    +  }
    +
    +  override def process(): Status = {
    +    // This method is called in a loop by the Flume framework - block it until the sink is
    +    // stopped to save CPU resources. The sink runner will interrupt this thread when the sink is
    +    // being shut down.
    +    blockingLatch.await()
    +    Status.BACKOFF
    +  }
    +}
    +
    +/**
    + * Class that implements the SparkFlumeProtocol, that is used by the Avro Netty Server to process
    + * requests. Each getEvents, ack and nack call is forwarded to an instance of this class.
    + * @param threads Number of threads to use to process requests.
    + * @param channel The channel that the sink pulls events from
    + * @param transactionTimeout Timeout in millis after which the transaction if not acked by Spark
    + *                           is rolled back.
    + */
    +private class SparkAvroCallbackHandler(val threads: Int, val channel: Channel,
    +  val transactionTimeout: Int) extends SparkFlumeProtocol {
    +  private val LOG = LoggerFactory.getLogger(classOf[SparkAvroCallbackHandler])
    +  val transactionExecutorOpt = Option(Executors.newFixedThreadPool(threads,
    +    new ThreadFactoryBuilder().setDaemon(true)
    +      .setNameFormat("Spark Sink Processor Thread - %d").build()))
    +  private val processorMap = new ConcurrentHashMap[CharSequence, TransactionProcessor]()
    +  // This sink will not persist sequence numbers and reuses them if it gets restarted.
    +  // So it is possible to commit a transaction which may have been meant for the sink before the
    +  // restart.
    +  // Since the new txn may not have the same sequence number we must guard against accidentally
    +  // committing a new transaction. To reduce the probability of that happening a random string is
    +  // prepended to the sequence number. Does not change for life of sink
    +  private val seqBase = RandomStringUtils.randomAlphanumeric(8)
    +  private val seqCounter = new AtomicLong(0)
    +
    +  /**
    +   * Returns a bunch of events to Spark over Avro RPC.
    +   * @param n Maximum number of events to return in a batch
    +   * @return [[EventBatch]] instance that has a sequence number and an array of at most n events
    +   */
    +  override def getEventBatch(n: Int): EventBatch = {
    +    val sequenceNumber = seqBase + seqCounter.incrementAndGet()
    +    val processor = new TransactionProcessor(channel, sequenceNumber,
    +      n, transactionTimeout, this)
    +    transactionExecutorOpt.map(executor => {
    +      executor.submit(processor)
    +    })
    +    // Wait until a batch is available - can be null if some error was thrown
    +    processor.getEventBatch match {
    +      case ErrorEventBatch => throw new FlumeException("Something went wrong. No events" +
    +        " retrieved from channel.")
    +      case eventBatch: EventBatch =>
    +        processorMap.put(sequenceNumber, processor)
    +        if (LOG.isDebugEnabled()) {
    +          LOG.debug("Sent " + eventBatch.getEvents.size() +
    +            " events with sequence number: " + eventBatch.getSequenceNumber)
    +        }
    +        eventBatch
    +    }
    +  }
    +
    +  /**
    +   * Called by Spark to indicate successful commit of a batch
    +   * @param sequenceNumber The sequence number of the event batch that was successful
    +   */
    +  override def ack(sequenceNumber: CharSequence): Void = {
    +    completeTransaction(sequenceNumber, success = true)
    +    null
    +  }
    +
    +  /**
    +   * Called by Spark to indicate failed commit of a batch
    +   * @param sequenceNumber The sequence number of the event batch that failed
    +   * @return
    +   */
    +  override def nack(sequenceNumber: CharSequence): Void = {
    +    completeTransaction(sequenceNumber, success = false)
    +    LOG.info("Spark failed to commit transaction. Will reattempt events.")
    +    null
    +  }
    +
    +  /**
    +   * Helper method to commit or rollback a transaction.
    +   * @param sequenceNumber The sequence number of the batch that was completed
    +   * @param success Whether the batch was successful or not.
    +   */
    +  private def completeTransaction(sequenceNumber: CharSequence, success: Boolean) {
    +    Option(removeAndGetProcessor(sequenceNumber)).map(processor => {
    +      processor.batchProcessed(success)
    +    })
    +  }
    +
    +  /**
    +   * Helper method to remove the TxnProcessor for a Sequence Number. Can be used to avoid a leak.
    +   * @param sequenceNumber
    +   * @return The transaction processor for the corresponding batch. Note that this instance is no
    +   *         longer tracked and the caller is responsible for that txn processor.
    +   */
    +  private[flume] def removeAndGetProcessor(sequenceNumber: CharSequence): TransactionProcessor = {
    +    processorMap.remove(sequenceNumber.toString) // The toString is required!
    +  }
    +
    +  /**
    +   * Shuts down the executor used to process transactions.
    +   */
    +  def shutdown() {
    +    transactionExecutorOpt.map(executor => {
    +      executor.shutdownNow()
    +    })
    +  }
    +}
    +
    +/**
    + * Object representing an empty batch returned by the txn processor due to some error.
    + */
    +case object ErrorEventBatch extends EventBatch
    +
    +// Flume forces transactions to be thread-local (horrible, I know!)
    +// So the sink basically spawns a new thread to pull the events out within a transaction.
    +// The thread fills in the event batch object that is set before the thread is scheduled.
    +// After filling it in, the thread waits on a condition - which is released only
    +// when the success message comes back for the specific sequence number for that event batch.
    +/**
    + * This class represents a transaction on the Flume channel. This class runs a separate thread
    + * which owns the transaction. The thread is blocked until the success call for that transaction
    + * comes back with an ACK or NACK.
    + * @param channel The channel from which to pull events
    + * @param seqNum The sequence number to use for the transaction. Must be unique
    + * @param maxBatchSize The maximum number of events to process per batch
    + * @param transactionTimeout Time in seconds after which a transaction must be rolled back
    + *                           without waiting for an ACK from Spark
    + * @param parent The parent [[SparkAvroCallbackHandler]] instance, for reporting timeouts
    + */
    +private class TransactionProcessor(val channel: Channel, val seqNum: String,
    +  var maxBatchSize: Int, val transactionTimeout: Int,
    +  val parent: SparkAvroCallbackHandler) extends Callable[Void] {
    +
    +  private val LOG = LoggerFactory.getLogger(classOf[TransactionProcessor])
    +
    +  // If a real batch is not returned, we always have to return an error batch.
    +  @volatile private var eventBatch: EventBatch = ErrorEventBatch
    +
    +  // Synchronization primitives
    +  val batchGeneratedLatch = new CountDownLatch(1)
    +  val batchAckLatch = new CountDownLatch(1)
    +
    +  // Sanity check to ensure we don't loop like crazy
    +  val totalAttemptsToRemoveFromChannel = Int.MaxValue / 2
    +
    +  // OK to use volatile, since the change would only make this true (otherwise it will be
    +  // changed to false - we never apply a negation operation to this) - which means the transaction
    +  // succeeded.
    +  @volatile private var batchSuccess = false
    +
    +  // The transaction that this processor would handle
    +  var txOpt: Option[Transaction] = None
    +
    +  /**
    +   * Get an event batch from the channel. This method will block until a batch of events is
    +   * available from the channel. If no events are available after a large number of attempts of
    +   * polling the channel, this method will return [[ErrorEventBatch]].
    +   *
    +   * @return An [[EventBatch]] instance with sequence number set to [[seqNum]], filled with a
    +   *         maximum of [[maxBatchSize]] events
    +   */
    +  def getEventBatch: EventBatch = {
    +    batchGeneratedLatch.await()
    +    eventBatch
    +  }
    +
    +  /**
    +   * This method is to be called by the sink when it receives an ACK or NACK from Spark. This
    +   * method is a no-op if it is called after [[transactionTimeout]] has expired since
    +   * [[getEventBatch]] returned a batch of events.
    +   * @param success True if an ACK was received and the transaction should be committed, else false.
    +   */
    +  def batchProcessed(success: Boolean) {
    +    if (LOG.isDebugEnabled) {
    +      LOG.debug("Batch processed for sequence number: " + seqNum)
    +    }
    +    batchSuccess = success
    +    batchAckLatch.countDown()
    +  }
    +
    +  /**
    +   * Populates events into the event batch. If the batch cannot be populated,
    +   * this method will not set the event batch which will stay [[ErrorEventBatch]]
    +   */
    +  private def populateEvents() {
    +    try {
    +      txOpt = Option(channel.getTransaction)
    +      txOpt.map(tx => {
    +        tx.begin()
    +        val events = new util.ArrayList[SparkSinkEvent](maxBatchSize)
    +        val loop = new Breaks
    +        var gotEventsInThisTxn = false
    +        var loopCounter: Int = 0
    +        loop.breakable {
    +          while (events.size() < maxBatchSize
    +            && loopCounter < totalAttemptsToRemoveFromChannel) {
    +            loopCounter += 1
    +            Option(channel.take()) match {
    +              case Some(event) =>
    +                events.add(new SparkSinkEvent(toCharSequenceMap(event.getHeaders),
    +                  ByteBuffer.wrap(event.getBody)))
    +                gotEventsInThisTxn = true
    +              case None =>
    +                if (!gotEventsInThisTxn) {
    +                  TimeUnit.MILLISECONDS.sleep(500)
    +                } else {
    +                  loop.break()
    +                }
    +            }
    +          }
    +        }
    +        if (!gotEventsInThisTxn) {
    +          throw new FlumeException("Tried too many times, didn't get any events from the channel")
    +        }
    +        // At this point, the events are available, so fill them into the event batch
    +        eventBatch = new EventBatch(seqNum, events)
    +      })
    +    } catch {
    +      case e: Throwable =>
    +        LOG.error("Error while processing transaction.", e)
    +        try {
    +          txOpt.map(tx => {
    +            rollbackAndClose(tx, close = true)
    +          })
    +        } finally {
    +          // Avro might serialize the exception and cause a NACK,
    +          // so don't bother with the transaction
    +          txOpt = None
    +        }
    +    } finally {
    +      batchGeneratedLatch.countDown()
    +    }
    +  }
    +
    +  /**
    +   * Waits for upto [[transactionTimeout]] seconds for an ACK. If an ACK comes in,
    +   * this method commits the transaction with the channel. If the ACK does not come in within
    +   * that time or a NACK comes in, this method rolls back the transaction.
    +   */
    +  private def processAckOrNack() {
    +    batchAckLatch.await(transactionTimeout, TimeUnit.SECONDS)
    +    txOpt.map(tx => {
    +      if (batchSuccess) {
    +        try {
    +          tx.commit()
    +        } catch {
    +          case e: Throwable =>
    +            rollbackAndClose(tx, close = false) // tx will be closed later anyway
    +        } finally {
    +          tx.close()
    --- End diff --
    
    Cool.


---
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 infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] spark pull request: SPARK-1729. Make Flume pull data from source, ...

Posted by tdas <gi...@git.apache.org>.
Github user tdas commented on a diff in the pull request:

    https://github.com/apache/spark/pull/807#discussion_r13465816
  
    --- Diff: external/flume-sink/src/main/scala/org/apache/spark/flume/sink/SparkSink.scala ---
    @@ -0,0 +1,392 @@
    +/*
    + * 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.flume.sink
    +
    +import org.apache.flume.sink.AbstractSink
    +import java.util.concurrent.locks.ReentrantLock
    +import org.apache.flume.Sink.Status
    +import org.apache.spark.flume.{SparkSinkEvent, EventBatch, SparkFlumeProtocol}
    +import scala.util.control.Breaks
    +import java.nio.ByteBuffer
    +import org.apache.flume.{FlumeException, Context}
    +import org.slf4j.LoggerFactory
    +import java.util.concurrent.atomic.AtomicLong
    +import org.apache.commons.lang.RandomStringUtils
    +import java.util.concurrent._
    +import java.util
    +import org.apache.flume.conf.{ConfigurationException, Configurable}
    +import com.google.common.util.concurrent.ThreadFactoryBuilder
    +import org.apache.avro.ipc.NettyServer
    +import org.apache.avro.ipc.specific.SpecificResponder
    +import java.net.InetSocketAddress
    +
    +class SparkSink() extends AbstractSink with Configurable {
    +  private val LOG = LoggerFactory.getLogger(this.getClass)
    +  private val lock = new ReentrantLock()
    +  private val blockingCondition = lock.newCondition()
    +
    +  // This sink will not persist sequence numbers and reuses them if it gets restarted.
    +  // So it is possible to commit a transaction which may have been meant for the sink before the
    +  // restart.
    +  // Since the new txn may not have the same sequence number we must guard against accidentally
    +  // committing
    +  // a new transaction. To reduce the probability of that happening a random string is prepended
    +  // to the sequence number.
    +  // Does not change for life of sink
    +  private val seqBase = RandomStringUtils.randomAlphanumeric(8)
    +  // Incremented for each transaction
    +  private val seqNum = new AtomicLong(0)
    +
    +  private var transactionExecutorOpt: Option[ExecutorService] = None
    +
    +  private var numProcessors: Integer = SparkSinkConfig.DEFAULT_PROCESSOR_COUNT
    +  private var transactionTimeout = SparkSinkConfig.DEFAULT_TRANSACTION_TIMEOUT
    +
    +  private val processorMap = new ConcurrentHashMap[CharSequence, TransactionProcessor]()
    +
    +  private var processorFactory: Option[SparkHandlerFactory] = None
    +  private var hostname: String = SparkSinkConfig.DEFAULT_HOSTNAME
    +  private var port: Int = 0
    +  private var maxThreads: Int = SparkSinkConfig.DEFAULT_MAX_THREADS
    +  private var serverOpt: Option[NettyServer] = None
    +  private var running = false
    +
    +  override def start() {
    +    transactionExecutorOpt = Option(Executors.newFixedThreadPool(numProcessors,
    +      new ThreadFactoryBuilder().setDaemon(true)
    +        .setNameFormat("Spark Sink, " + getName + " Processor Thread - %d").build()))
    +
    +    processorFactory = Option(new SparkHandlerFactory(numProcessors))
    +
    +    val responder = new SpecificResponder(classOf[SparkFlumeProtocol], new AvroCallbackHandler())
    +
    +    // Using the constructor that takes specific thread-pools requires bringing in netty
    +    // dependencies which are being excluded in the build. In practice,
    +    // Netty dependencies are already available on the JVM as Flume would have pulled them in.
    +    serverOpt = Option(new NettyServer(responder, new InetSocketAddress(hostname, port)))
    +
    +    serverOpt.map(server => server.start())
    +    lock.lock()
    +    try {
    +      running = true
    +    } finally {
    +      lock.unlock()
    +    }
    +    super.start()
    +  }
    +
    +  override def stop() {
    +    transactionExecutorOpt.map(executor => executor.shutdownNow())
    +    serverOpt.map(server => {
    +      server.close()
    +      server.join()
    +    })
    +    lock.lock()
    +    try {
    +      running = false
    +      blockingCondition.signalAll()
    +    } finally {
    +      lock.unlock()
    +    }
    +  }
    +
    +  override def configure(ctx: Context) {
    +    import SparkSinkConfig._
    +    hostname = ctx.getString(CONF_HOSTNAME, DEFAULT_HOSTNAME)
    +    val portOpt = Option(ctx.getInteger(CONF_PORT))
    +    if(portOpt.isDefined) {
    +      port = portOpt.get
    +    } else {
    +      throw new ConfigurationException("The Port to bind must be specified")
    +    }
    +    numProcessors = ctx.getInteger(PROCESSOR_COUNT, DEFAULT_PROCESSOR_COUNT)
    +    transactionTimeout = ctx.getInteger(CONF_TRANSACTION_TIMEOUT, DEFAULT_TRANSACTION_TIMEOUT)
    +    maxThreads = ctx.getInteger(CONF_MAX_THREADS, DEFAULT_MAX_THREADS)
    +  }
    +
    +  override def process(): Status = {
    +    // This method is called in a loop by the Flume framework - block it until the sink is
    +    // stopped to save CPU resources
    +    lock.lock()
    +    try {
    +      while(running) {
    +        blockingCondition.await()
    +      }
    +    } finally {
    +      lock.unlock()
    +    }
    +    Status.BACKOFF
    +  }
    +
    +
    +  // Object representing an empty batch returned by the txn processor due to some error.
    +  case object ErrorEventBatch extends EventBatch
    +
    +  private class AvroCallbackHandler() extends SparkFlumeProtocol {
    +
    +    override def getEventBatch(n: Int): EventBatch = {
    +      val processor = processorFactory.get.checkOut(n)
    +      transactionExecutorOpt.map(executor => executor.submit(processor))
    +      // Wait until a batch is available - can be null if some error was thrown
    +      val eventBatch = processor.eventQueue.take()
    +      eventBatch match {
    +        case ErrorEventBatch => throw new FlumeException("Something went wrong. No events" +
    +          " retrieved from channel.")
    +        case events => {
    +          processorMap.put(events.getSequenceNumber, processor)
    +          if (LOG.isDebugEnabled) {
    +            LOG.debug("Sent " + events.getEventBatch.size() +
    +              " events with sequence number: " + events.getSequenceNumber)
    +          }
    +          events
    +        }
    +      }
    +    }
    +
    +    override def ack(sequenceNumber: CharSequence): Void = {
    +      completeTransaction(sequenceNumber, success = true)
    +      null
    +    }
    +
    +    override def nack(sequenceNumber: CharSequence): Void = {
    +      completeTransaction(sequenceNumber, success = false)
    +      LOG.info("Spark failed to commit transaction. Will reattempt events.")
    +      null
    +    }
    +
    +    def completeTransaction(sequenceNumber: CharSequence, success: Boolean) {
    +      val processorOpt = Option(processorMap.remove(sequenceNumber))
    +      if (processorOpt.isDefined) {
    +        val processor = processorOpt.get
    +        processor.resultQueueUpdateLock.lock()
    +        try {
    +          // Is the sequence number the same as the one the processor is processing? If not,
    +          // don't update {
    +          if (processor.eventBatch.getSequenceNumber.equals(sequenceNumber)) {
    +            processor.resultQueue.put(success)
    +          }
    +        } finally {
    +          processor.resultQueueUpdateLock.unlock()
    +        }
    +      }
    +    }
    +  }
    +
    +  // Flume forces transactions to be thread-local (horrible, I know!)
    +  // So the sink basically spawns a new thread to pull the events out within a transaction.
    +  // The thread fills in the event batch object that is set before the thread is scheduled.
    +  // After filling it in, the thread waits on a condition - which is released only
    +  // when the success message comes back for the specific sequence number for that event batch.
    +  /**
    +   * This class represents a transaction on the Flume channel. This class runs a separate thread
    +   * which owns the transaction. It is blocked until the success call for that transaction comes
    +   * back.
    +   * @param maxBatchSize
    +   */
    +  private class TransactionProcessor(var maxBatchSize: Int) extends Callable[Void] {
    +    // Must be set to a new event batch before scheduling this!!
    +    val eventBatch = new EventBatch("", new util.LinkedList[SparkSinkEvent])
    +    val eventQueue = new SynchronousQueue[EventBatch]()
    +    val resultQueue = new SynchronousQueue[Boolean]()
    +    val resultQueueUpdateLock = new ReentrantLock()
    +
    +    object Zero {
    +      val zero = "0" // Oh, I miss static finals
    +    }
    +
    +
    +    override def call(): Void = {
    +      val tx = getChannel.getTransaction
    +      tx.begin()
    +      try {
    +        eventBatch.setSequenceNumber(seqBase + seqNum.incrementAndGet())
    +        val events = eventBatch.getEventBatch
    +        events.clear()
    +        val loop = new Breaks
    +        var gotEventsInThisTxn = false
    +        loop.breakable {
    +          var i = 0
    +          // Using for here causes the maxBatchSize change to be ineffective as the Range gets
    +          // pregenerated
    +          while (i < maxBatchSize) {
    +            i += 1
    +            val eventOpt = Option(getChannel.take())
    +            eventOpt.map(event => {
    +              events.add(new SparkSinkEvent(toCharSequenceMap(event
    +                .getHeaders),
    +                ByteBuffer.wrap(event.getBody)))
    +              gotEventsInThisTxn = true
    +            })
    +            if (eventOpt.isEmpty) {
    +              if (!gotEventsInThisTxn) {
    +                // To avoid sending empty batches, we wait till events are available backing off
    +                // between attempts to get events. Each attempt to get an event though causes one
    +                // iteration to be lost. To ensure that we still send back maxBatchSize number of
    +                // events, we cheat and increase the maxBatchSize by 1 to account for the lost
    +                // iteration. Even throwing an exception is expensive as Avro will serialize it
    +                // and send it over the wire, which is useless. Before incrementing though,
    +                // ensure that we are not anywhere near INT_MAX.
    +                if (maxBatchSize >= Int.MaxValue / 2) {
    +                  // Random sanity check
    +                  throw new RuntimeException("Safety exception - polled too many times, no events!")
    +                }
    +                maxBatchSize += 1
    +                Thread.sleep(500)
    +              } else {
    +                loop.break()
    +              }
    +            }
    +          }
    +        }
    +        // Make the data available to the sender thread
    +        eventQueue.put(eventBatch)
    +
    +        // Wait till timeout for the ack/nack
    +        val maybeResult = Option(resultQueue.poll(transactionTimeout, TimeUnit.SECONDS))
    +        // There is a race condition here.
    +        // 1. This times out.
    +        // 2. The result is empty, so timeout exception is thrown.
    +        // 3. The ack comes in before the finally block is entered
    +        // 4. The thread with the ack has a handle to this processor,
    +        // and another thread has the same processor checked out
    +        // (since the finally block was executed and the processor checked back in)
    +        // 5. The thread with the ack now updates the result queue,
    +        // so the processor thinks it is the ack for the current batch.
    +        // To avoid this - update the sequence number to "0" (with or without a result - does not
    +        // matter).
    +        // In the ack method, check if the seq number is the same as the processor's -
    +        // if they are then update the result queue. Now if the
    +        // processor updates the seq number first - the ack/nack never updates the result. If the
    +        // ack/nack updates the
    +        // result after the timeout but before the seq number is updated to "0" it does not
    +        // matter - the processor would
    +        // still timeout and the result is cleared before reusing the processor.
    +        // Unfortunately, this needs to be done from within a lock
    +        // to make sure that the new sequence number is actually visible to the ack thread
    +        // (happens-before)
    +        resultQueueUpdateLock.lock()
    +        try {
    +          eventBatch.setSequenceNumber(Zero.zero)
    +        } finally {
    +          resultQueueUpdateLock.unlock()
    +        }
    +        eventBatch.getEventBatch.clear()
    +        // If the batch failed on spark side, throw a FlumeException
    +        maybeResult.map(success =>
    +          if (!success) {
    +            throw new
    +                FlumeException("Spark could not accept events. The transaction will be retried.")
    +          }
    +        )
    +        // If the operation timed out, throw a TimeoutException
    +        if (maybeResult.isEmpty) {
    +          throw new TimeoutException("Spark did not respond within the timeout period of " +
    +            transactionTimeout + "seconds. Transaction will be retried")
    +        }
    +        null
    +      } catch {
    +        case e: Throwable =>
    +          try {
    +            LOG.warn("Error while attempting to remove events from the channel.", e)
    +            tx.rollback()
    +          } catch {
    +            case e1: Throwable => LOG.error(
    +              "Rollback failed while attempting to rollback due to commit failure.", e1)
    +          }
    +          null // No point rethrowing the exception
    +      } finally {
    +        // Must *always* release the caller thread
    +        eventQueue.put(ErrorEventBatch)
    +        // In the case of success coming after the timeout, but before resetting the seq number
    +        // remove the event from the map and then clear the value
    +        resultQueue.clear()
    +        processorMap.remove(eventBatch.getSequenceNumber)
    +        processorFactory.get.checkIn(this)
    +        tx.close()
    +      }
    +    }
    +
    +    def toCharSequenceMap(inMap: java.util.Map[String, String]): java.util.Map[CharSequence,
    +      CharSequence] = {
    +      val charSeqMap = new util.HashMap[CharSequence, CharSequence](inMap.size())
    +      charSeqMap.putAll(inMap)
    +      charSeqMap
    +    }
    +  }
    +
    +  private class SparkHandlerFactory(val maxInstances: Int) {
    +    val queue = new scala.collection.mutable.Queue[TransactionProcessor]
    --- End diff --
    
    Can you please add what is the intended functionality of this class? Also, `XYZFactory` is supposed to create instances of `XYZ`. That does not seem to be the case here. A little non-intuitive.


---
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 infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] spark pull request: SPARK-1729. Make Flume pull data from source, ...

Posted by tdas <gi...@git.apache.org>.
Github user tdas commented on a diff in the pull request:

    https://github.com/apache/spark/pull/807#discussion_r13472548
  
    --- Diff: external/flume-sink/src/main/scala/org/apache/spark/flume/sink/SparkSink.scala ---
    @@ -0,0 +1,392 @@
    +/*
    + * 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.flume.sink
    +
    +import org.apache.flume.sink.AbstractSink
    +import java.util.concurrent.locks.ReentrantLock
    +import org.apache.flume.Sink.Status
    +import org.apache.spark.flume.{SparkSinkEvent, EventBatch, SparkFlumeProtocol}
    +import scala.util.control.Breaks
    +import java.nio.ByteBuffer
    +import org.apache.flume.{FlumeException, Context}
    +import org.slf4j.LoggerFactory
    +import java.util.concurrent.atomic.AtomicLong
    +import org.apache.commons.lang.RandomStringUtils
    +import java.util.concurrent._
    +import java.util
    +import org.apache.flume.conf.{ConfigurationException, Configurable}
    +import com.google.common.util.concurrent.ThreadFactoryBuilder
    +import org.apache.avro.ipc.NettyServer
    +import org.apache.avro.ipc.specific.SpecificResponder
    +import java.net.InetSocketAddress
    +
    +class SparkSink() extends AbstractSink with Configurable {
    +  private val LOG = LoggerFactory.getLogger(this.getClass)
    +  private val lock = new ReentrantLock()
    +  private val blockingCondition = lock.newCondition()
    +
    +  // This sink will not persist sequence numbers and reuses them if it gets restarted.
    +  // So it is possible to commit a transaction which may have been meant for the sink before the
    +  // restart.
    +  // Since the new txn may not have the same sequence number we must guard against accidentally
    +  // committing
    +  // a new transaction. To reduce the probability of that happening a random string is prepended
    +  // to the sequence number.
    +  // Does not change for life of sink
    +  private val seqBase = RandomStringUtils.randomAlphanumeric(8)
    +  // Incremented for each transaction
    +  private val seqNum = new AtomicLong(0)
    +
    +  private var transactionExecutorOpt: Option[ExecutorService] = None
    +
    +  private var numProcessors: Integer = SparkSinkConfig.DEFAULT_PROCESSOR_COUNT
    +  private var transactionTimeout = SparkSinkConfig.DEFAULT_TRANSACTION_TIMEOUT
    +
    +  private val processorMap = new ConcurrentHashMap[CharSequence, TransactionProcessor]()
    +
    +  private var processorFactory: Option[SparkHandlerFactory] = None
    +  private var hostname: String = SparkSinkConfig.DEFAULT_HOSTNAME
    +  private var port: Int = 0
    +  private var maxThreads: Int = SparkSinkConfig.DEFAULT_MAX_THREADS
    +  private var serverOpt: Option[NettyServer] = None
    +  private var running = false
    +
    +  override def start() {
    +    transactionExecutorOpt = Option(Executors.newFixedThreadPool(numProcessors,
    +      new ThreadFactoryBuilder().setDaemon(true)
    +        .setNameFormat("Spark Sink, " + getName + " Processor Thread - %d").build()))
    +
    +    processorFactory = Option(new SparkHandlerFactory(numProcessors))
    +
    +    val responder = new SpecificResponder(classOf[SparkFlumeProtocol], new AvroCallbackHandler())
    +
    +    // Using the constructor that takes specific thread-pools requires bringing in netty
    +    // dependencies which are being excluded in the build. In practice,
    +    // Netty dependencies are already available on the JVM as Flume would have pulled them in.
    +    serverOpt = Option(new NettyServer(responder, new InetSocketAddress(hostname, port)))
    +
    +    serverOpt.map(server => server.start())
    +    lock.lock()
    +    try {
    +      running = true
    +    } finally {
    +      lock.unlock()
    +    }
    +    super.start()
    +  }
    +
    +  override def stop() {
    +    transactionExecutorOpt.map(executor => executor.shutdownNow())
    +    serverOpt.map(server => {
    +      server.close()
    +      server.join()
    +    })
    +    lock.lock()
    +    try {
    +      running = false
    +      blockingCondition.signalAll()
    +    } finally {
    +      lock.unlock()
    +    }
    +  }
    +
    +  override def configure(ctx: Context) {
    +    import SparkSinkConfig._
    +    hostname = ctx.getString(CONF_HOSTNAME, DEFAULT_HOSTNAME)
    +    val portOpt = Option(ctx.getInteger(CONF_PORT))
    +    if(portOpt.isDefined) {
    +      port = portOpt.get
    +    } else {
    +      throw new ConfigurationException("The Port to bind must be specified")
    +    }
    +    numProcessors = ctx.getInteger(PROCESSOR_COUNT, DEFAULT_PROCESSOR_COUNT)
    +    transactionTimeout = ctx.getInteger(CONF_TRANSACTION_TIMEOUT, DEFAULT_TRANSACTION_TIMEOUT)
    +    maxThreads = ctx.getInteger(CONF_MAX_THREADS, DEFAULT_MAX_THREADS)
    +  }
    +
    +  override def process(): Status = {
    +    // This method is called in a loop by the Flume framework - block it until the sink is
    +    // stopped to save CPU resources
    +    lock.lock()
    +    try {
    +      while(running) {
    +        blockingCondition.await()
    +      }
    +    } finally {
    +      lock.unlock()
    +    }
    +    Status.BACKOFF
    +  }
    +
    +
    +  // Object representing an empty batch returned by the txn processor due to some error.
    +  case object ErrorEventBatch extends EventBatch
    +
    +  private class AvroCallbackHandler() extends SparkFlumeProtocol {
    +
    +    override def getEventBatch(n: Int): EventBatch = {
    +      val processor = processorFactory.get.checkOut(n)
    +      transactionExecutorOpt.map(executor => executor.submit(processor))
    +      // Wait until a batch is available - can be null if some error was thrown
    +      val eventBatch = processor.eventQueue.take()
    +      eventBatch match {
    +        case ErrorEventBatch => throw new FlumeException("Something went wrong. No events" +
    +          " retrieved from channel.")
    +        case events => {
    +          processorMap.put(events.getSequenceNumber, processor)
    +          if (LOG.isDebugEnabled) {
    +            LOG.debug("Sent " + events.getEventBatch.size() +
    +              " events with sequence number: " + events.getSequenceNumber)
    +          }
    +          events
    +        }
    +      }
    +    }
    +
    +    override def ack(sequenceNumber: CharSequence): Void = {
    +      completeTransaction(sequenceNumber, success = true)
    +      null
    +    }
    +
    +    override def nack(sequenceNumber: CharSequence): Void = {
    +      completeTransaction(sequenceNumber, success = false)
    +      LOG.info("Spark failed to commit transaction. Will reattempt events.")
    +      null
    +    }
    +
    +    def completeTransaction(sequenceNumber: CharSequence, success: Boolean) {
    +      val processorOpt = Option(processorMap.remove(sequenceNumber))
    +      if (processorOpt.isDefined) {
    +        val processor = processorOpt.get
    +        processor.resultQueueUpdateLock.lock()
    +        try {
    +          // Is the sequence number the same as the one the processor is processing? If not,
    +          // don't update {
    +          if (processor.eventBatch.getSequenceNumber.equals(sequenceNumber)) {
    +            processor.resultQueue.put(success)
    +          }
    +        } finally {
    +          processor.resultQueueUpdateLock.unlock()
    +        }
    +      }
    +    }
    +  }
    +
    +  // Flume forces transactions to be thread-local (horrible, I know!)
    +  // So the sink basically spawns a new thread to pull the events out within a transaction.
    +  // The thread fills in the event batch object that is set before the thread is scheduled.
    +  // After filling it in, the thread waits on a condition - which is released only
    +  // when the success message comes back for the specific sequence number for that event batch.
    +  /**
    +   * This class represents a transaction on the Flume channel. This class runs a separate thread
    +   * which owns the transaction. It is blocked until the success call for that transaction comes
    +   * back.
    +   * @param maxBatchSize
    +   */
    +  private class TransactionProcessor(var maxBatchSize: Int) extends Callable[Void] {
    +    // Must be set to a new event batch before scheduling this!!
    +    val eventBatch = new EventBatch("", new util.LinkedList[SparkSinkEvent])
    +    val eventQueue = new SynchronousQueue[EventBatch]()
    +    val resultQueue = new SynchronousQueue[Boolean]()
    +    val resultQueueUpdateLock = new ReentrantLock()
    +
    +    object Zero {
    +      val zero = "0" // Oh, I miss static finals
    +    }
    +
    +
    +    override def call(): Void = {
    +      val tx = getChannel.getTransaction
    +      tx.begin()
    +      try {
    +        eventBatch.setSequenceNumber(seqBase + seqNum.incrementAndGet())
    +        val events = eventBatch.getEventBatch
    +        events.clear()
    +        val loop = new Breaks
    +        var gotEventsInThisTxn = false
    +        loop.breakable {
    +          var i = 0
    +          // Using for here causes the maxBatchSize change to be ineffective as the Range gets
    +          // pregenerated
    +          while (i < maxBatchSize) {
    +            i += 1
    +            val eventOpt = Option(getChannel.take())
    +            eventOpt.map(event => {
    +              events.add(new SparkSinkEvent(toCharSequenceMap(event
    +                .getHeaders),
    +                ByteBuffer.wrap(event.getBody)))
    +              gotEventsInThisTxn = true
    +            })
    +            if (eventOpt.isEmpty) {
    +              if (!gotEventsInThisTxn) {
    +                // To avoid sending empty batches, we wait till events are available backing off
    +                // between attempts to get events. Each attempt to get an event though causes one
    +                // iteration to be lost. To ensure that we still send back maxBatchSize number of
    +                // events, we cheat and increase the maxBatchSize by 1 to account for the lost
    +                // iteration. Even throwing an exception is expensive as Avro will serialize it
    +                // and send it over the wire, which is useless. Before incrementing though,
    +                // ensure that we are not anywhere near INT_MAX.
    +                if (maxBatchSize >= Int.MaxValue / 2) {
    +                  // Random sanity check
    +                  throw new RuntimeException("Safety exception - polled too many times, no events!")
    +                }
    +                maxBatchSize += 1
    +                Thread.sleep(500)
    +              } else {
    +                loop.break()
    +              }
    +            }
    +          }
    +        }
    +        // Make the data available to the sender thread
    +        eventQueue.put(eventBatch)
    +
    +        // Wait till timeout for the ack/nack
    +        val maybeResult = Option(resultQueue.poll(transactionTimeout, TimeUnit.SECONDS))
    +        // There is a race condition here.
    +        // 1. This times out.
    +        // 2. The result is empty, so timeout exception is thrown.
    +        // 3. The ack comes in before the finally block is entered
    +        // 4. The thread with the ack has a handle to this processor,
    +        // and another thread has the same processor checked out
    +        // (since the finally block was executed and the processor checked back in)
    +        // 5. The thread with the ack now updates the result queue,
    +        // so the processor thinks it is the ack for the current batch.
    +        // To avoid this - update the sequence number to "0" (with or without a result - does not
    +        // matter).
    +        // In the ack method, check if the seq number is the same as the processor's -
    +        // if they are then update the result queue. Now if the
    +        // processor updates the seq number first - the ack/nack never updates the result. If the
    +        // ack/nack updates the
    +        // result after the timeout but before the seq number is updated to "0" it does not
    +        // matter - the processor would
    +        // still timeout and the result is cleared before reusing the processor.
    +        // Unfortunately, this needs to be done from within a lock
    +        // to make sure that the new sequence number is actually visible to the ack thread
    +        // (happens-before)
    +        resultQueueUpdateLock.lock()
    +        try {
    +          eventBatch.setSequenceNumber(Zero.zero)
    +        } finally {
    +          resultQueueUpdateLock.unlock()
    +        }
    +        eventBatch.getEventBatch.clear()
    +        // If the batch failed on spark side, throw a FlumeException
    +        maybeResult.map(success =>
    +          if (!success) {
    +            throw new
    +                FlumeException("Spark could not accept events. The transaction will be retried.")
    +          }
    +        )
    +        // If the operation timed out, throw a TimeoutException
    +        if (maybeResult.isEmpty) {
    +          throw new TimeoutException("Spark did not respond within the timeout period of " +
    +            transactionTimeout + "seconds. Transaction will be retried")
    +        }
    +        null
    +      } catch {
    +        case e: Throwable =>
    +          try {
    +            LOG.warn("Error while attempting to remove events from the channel.", e)
    +            tx.rollback()
    +          } catch {
    +            case e1: Throwable => LOG.error(
    +              "Rollback failed while attempting to rollback due to commit failure.", e1)
    +          }
    +          null // No point rethrowing the exception
    +      } finally {
    +        // Must *always* release the caller thread
    +        eventQueue.put(ErrorEventBatch)
    +        // In the case of success coming after the timeout, but before resetting the seq number
    +        // remove the event from the map and then clear the value
    +        resultQueue.clear()
    +        processorMap.remove(eventBatch.getSequenceNumber)
    +        processorFactory.get.checkIn(this)
    +        tx.close()
    +      }
    +    }
    +
    +    def toCharSequenceMap(inMap: java.util.Map[String, String]): java.util.Map[CharSequence,
    +      CharSequence] = {
    +      val charSeqMap = new util.HashMap[CharSequence, CharSequence](inMap.size())
    +      charSeqMap.putAll(inMap)
    +      charSeqMap
    +    }
    +  }
    +
    +  private class SparkHandlerFactory(val maxInstances: Int) {
    +    val queue = new scala.collection.mutable.Queue[TransactionProcessor]
    +    val queueModificationLock = new ReentrantLock()
    +    var currentSize = 0
    +    val waitForCheckIn = queueModificationLock.newCondition()
    +
    +    def checkOut(n: Int): TransactionProcessor = {
    +      def getProcessor = {
    +        val processor = queue.dequeue()
    +        processor.maxBatchSize = n
    +        processor
    +      }
    +      queueModificationLock.lock()
    +      try {
    +        if (queue.size > 0) {
    +          getProcessor
    +        }
    +        else {
    +          if (currentSize < maxInstances) {
    +            currentSize += 1
    --- End diff --
    
    Right! My bad I missed that. 


---
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 infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] spark pull request: SPARK-1729. Make Flume pull data from source, ...

Posted by harishreedharan <gi...@git.apache.org>.
Github user harishreedharan commented on the pull request:

    https://github.com/apache/spark/pull/807#issuecomment-49673909
  
    Looks like a missing ASF header in JavaFlumePollingStreamSuite


---
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 infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] spark pull request: SPARK-1729. Make Flume pull data from source, ...

Posted by harishreedharan <gi...@git.apache.org>.
Github user harishreedharan commented on the pull request:

    https://github.com/apache/spark/pull/807#issuecomment-49704453
  
    Thanks for taking a look Patrick. The reason this really is not going into Flume itself is that Flume sinks are push model (this sink is hacking around it). For now, I don't expect a polling model sink to get committed to Flume, plus this is a very special case compared to the normal sinks - and it is more specific than general purpose.
    
    I will look into that SparkFlumeEvent - for now, it seems like it should be possible. Will update this later if needed.


---
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 infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] spark pull request: SPARK-1729. Make Flume pull data from source, ...

Posted by rxin <gi...@git.apache.org>.
Github user rxin commented on a diff in the pull request:

    https://github.com/apache/spark/pull/807#discussion_r13426078
  
    --- Diff: external/flume-sink/src/main/scala/org/apache/spark/flume/sink/SparkSink.scala ---
    @@ -0,0 +1,392 @@
    +/*
    + * 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.flume.sink
    +
    +import org.apache.flume.sink.AbstractSink
    +import java.util.concurrent.locks.ReentrantLock
    +import org.apache.flume.Sink.Status
    +import org.apache.spark.flume.{SparkSinkEvent, EventBatch, SparkFlumeProtocol}
    +import scala.util.control.Breaks
    +import java.nio.ByteBuffer
    +import org.apache.flume.{FlumeException, Context}
    +import org.slf4j.LoggerFactory
    +import java.util.concurrent.atomic.AtomicLong
    +import org.apache.commons.lang.RandomStringUtils
    +import java.util.concurrent._
    +import java.util
    +import org.apache.flume.conf.{ConfigurationException, Configurable}
    +import com.google.common.util.concurrent.ThreadFactoryBuilder
    +import org.apache.avro.ipc.NettyServer
    +import org.apache.avro.ipc.specific.SpecificResponder
    +import java.net.InetSocketAddress
    +
    +class SparkSink() extends AbstractSink with Configurable {
    +  private val LOG = LoggerFactory.getLogger(this.getClass)
    +  private val lock = new ReentrantLock()
    +  private val blockingCondition = lock.newCondition()
    --- End diff --
    
    j.u.c.l locks in general perform better than synchronized when there are some contention. However, if there are no contention at all, synchronized is much cheaper due to bias locking.


---
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 infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] spark pull request: SPARK-1729. Make Flume pull data from source, ...

Posted by harishreedharan <gi...@git.apache.org>.
Github user harishreedharan commented on the pull request:

    https://github.com/apache/spark/pull/807#issuecomment-44043821
  
    I am going to update this to support polling from multiple Flume agents rather than just one.


---
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 infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] spark pull request: SPARK-1729. Make Flume pull data from source, ...

Posted by tdas <gi...@git.apache.org>.
Github user tdas commented on a diff in the pull request:

    https://github.com/apache/spark/pull/807#discussion_r13419880
  
    --- Diff: external/flume-sink/src/main/scala/org/apache/spark/flume/sink/SparkSink.scala ---
    @@ -0,0 +1,392 @@
    +/*
    + * 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.flume.sink
    +
    +import org.apache.flume.sink.AbstractSink
    +import java.util.concurrent.locks.ReentrantLock
    +import org.apache.flume.Sink.Status
    +import org.apache.spark.flume.{SparkSinkEvent, EventBatch, SparkFlumeProtocol}
    +import scala.util.control.Breaks
    +import java.nio.ByteBuffer
    +import org.apache.flume.{FlumeException, Context}
    +import org.slf4j.LoggerFactory
    +import java.util.concurrent.atomic.AtomicLong
    +import org.apache.commons.lang.RandomStringUtils
    +import java.util.concurrent._
    +import java.util
    +import org.apache.flume.conf.{ConfigurationException, Configurable}
    +import com.google.common.util.concurrent.ThreadFactoryBuilder
    +import org.apache.avro.ipc.NettyServer
    +import org.apache.avro.ipc.specific.SpecificResponder
    +import java.net.InetSocketAddress
    +
    +class SparkSink() extends AbstractSink with Configurable {
    +  private val LOG = LoggerFactory.getLogger(this.getClass)
    +  private val lock = new ReentrantLock()
    +  private val blockingCondition = lock.newCondition()
    --- End diff --
    
    Interesting! Can you point me towards any documentation that suggests that locks perform better than synchronized in some JVMs? I would like to learn more. 


---
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 infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] spark pull request: SPARK-1729. Make Flume pull data from source, ...

Posted by tdas <gi...@git.apache.org>.
Github user tdas commented on a diff in the pull request:

    https://github.com/apache/spark/pull/807#discussion_r13467330
  
    --- Diff: external/flume-sink/src/main/scala/org/apache/spark/flume/sink/SparkSink.scala ---
    @@ -0,0 +1,392 @@
    +/*
    + * 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.flume.sink
    +
    +import org.apache.flume.sink.AbstractSink
    +import java.util.concurrent.locks.ReentrantLock
    +import org.apache.flume.Sink.Status
    +import org.apache.spark.flume.{SparkSinkEvent, EventBatch, SparkFlumeProtocol}
    +import scala.util.control.Breaks
    +import java.nio.ByteBuffer
    +import org.apache.flume.{FlumeException, Context}
    +import org.slf4j.LoggerFactory
    +import java.util.concurrent.atomic.AtomicLong
    +import org.apache.commons.lang.RandomStringUtils
    +import java.util.concurrent._
    +import java.util
    +import org.apache.flume.conf.{ConfigurationException, Configurable}
    +import com.google.common.util.concurrent.ThreadFactoryBuilder
    +import org.apache.avro.ipc.NettyServer
    +import org.apache.avro.ipc.specific.SpecificResponder
    +import java.net.InetSocketAddress
    +
    +class SparkSink() extends AbstractSink with Configurable {
    +  private val LOG = LoggerFactory.getLogger(this.getClass)
    +  private val lock = new ReentrantLock()
    +  private val blockingCondition = lock.newCondition()
    +
    +  // This sink will not persist sequence numbers and reuses them if it gets restarted.
    +  // So it is possible to commit a transaction which may have been meant for the sink before the
    +  // restart.
    +  // Since the new txn may not have the same sequence number we must guard against accidentally
    +  // committing
    +  // a new transaction. To reduce the probability of that happening a random string is prepended
    +  // to the sequence number.
    +  // Does not change for life of sink
    +  private val seqBase = RandomStringUtils.randomAlphanumeric(8)
    +  // Incremented for each transaction
    +  private val seqNum = new AtomicLong(0)
    +
    +  private var transactionExecutorOpt: Option[ExecutorService] = None
    +
    +  private var numProcessors: Integer = SparkSinkConfig.DEFAULT_PROCESSOR_COUNT
    +  private var transactionTimeout = SparkSinkConfig.DEFAULT_TRANSACTION_TIMEOUT
    +
    +  private val processorMap = new ConcurrentHashMap[CharSequence, TransactionProcessor]()
    +
    +  private var processorFactory: Option[SparkHandlerFactory] = None
    +  private var hostname: String = SparkSinkConfig.DEFAULT_HOSTNAME
    +  private var port: Int = 0
    +  private var maxThreads: Int = SparkSinkConfig.DEFAULT_MAX_THREADS
    +  private var serverOpt: Option[NettyServer] = None
    +  private var running = false
    +
    +  override def start() {
    +    transactionExecutorOpt = Option(Executors.newFixedThreadPool(numProcessors,
    +      new ThreadFactoryBuilder().setDaemon(true)
    +        .setNameFormat("Spark Sink, " + getName + " Processor Thread - %d").build()))
    +
    +    processorFactory = Option(new SparkHandlerFactory(numProcessors))
    +
    +    val responder = new SpecificResponder(classOf[SparkFlumeProtocol], new AvroCallbackHandler())
    +
    +    // Using the constructor that takes specific thread-pools requires bringing in netty
    +    // dependencies which are being excluded in the build. In practice,
    +    // Netty dependencies are already available on the JVM as Flume would have pulled them in.
    +    serverOpt = Option(new NettyServer(responder, new InetSocketAddress(hostname, port)))
    +
    +    serverOpt.map(server => server.start())
    +    lock.lock()
    +    try {
    +      running = true
    +    } finally {
    +      lock.unlock()
    +    }
    +    super.start()
    +  }
    +
    +  override def stop() {
    +    transactionExecutorOpt.map(executor => executor.shutdownNow())
    +    serverOpt.map(server => {
    +      server.close()
    +      server.join()
    +    })
    +    lock.lock()
    +    try {
    +      running = false
    +      blockingCondition.signalAll()
    +    } finally {
    +      lock.unlock()
    +    }
    +  }
    +
    +  override def configure(ctx: Context) {
    +    import SparkSinkConfig._
    +    hostname = ctx.getString(CONF_HOSTNAME, DEFAULT_HOSTNAME)
    +    val portOpt = Option(ctx.getInteger(CONF_PORT))
    +    if(portOpt.isDefined) {
    +      port = portOpt.get
    +    } else {
    +      throw new ConfigurationException("The Port to bind must be specified")
    +    }
    +    numProcessors = ctx.getInteger(PROCESSOR_COUNT, DEFAULT_PROCESSOR_COUNT)
    +    transactionTimeout = ctx.getInteger(CONF_TRANSACTION_TIMEOUT, DEFAULT_TRANSACTION_TIMEOUT)
    +    maxThreads = ctx.getInteger(CONF_MAX_THREADS, DEFAULT_MAX_THREADS)
    +  }
    +
    +  override def process(): Status = {
    +    // This method is called in a loop by the Flume framework - block it until the sink is
    +    // stopped to save CPU resources
    +    lock.lock()
    +    try {
    +      while(running) {
    +        blockingCondition.await()
    +      }
    +    } finally {
    +      lock.unlock()
    +    }
    +    Status.BACKOFF
    +  }
    +
    +
    +  // Object representing an empty batch returned by the txn processor due to some error.
    +  case object ErrorEventBatch extends EventBatch
    +
    +  private class AvroCallbackHandler() extends SparkFlumeProtocol {
    +
    +    override def getEventBatch(n: Int): EventBatch = {
    +      val processor = processorFactory.get.checkOut(n)
    +      transactionExecutorOpt.map(executor => executor.submit(processor))
    +      // Wait until a batch is available - can be null if some error was thrown
    +      val eventBatch = processor.eventQueue.take()
    +      eventBatch match {
    +        case ErrorEventBatch => throw new FlumeException("Something went wrong. No events" +
    +          " retrieved from channel.")
    +        case events => {
    +          processorMap.put(events.getSequenceNumber, processor)
    +          if (LOG.isDebugEnabled) {
    +            LOG.debug("Sent " + events.getEventBatch.size() +
    +              " events with sequence number: " + events.getSequenceNumber)
    +          }
    +          events
    +        }
    +      }
    +    }
    +
    +    override def ack(sequenceNumber: CharSequence): Void = {
    +      completeTransaction(sequenceNumber, success = true)
    +      null
    +    }
    +
    +    override def nack(sequenceNumber: CharSequence): Void = {
    +      completeTransaction(sequenceNumber, success = false)
    +      LOG.info("Spark failed to commit transaction. Will reattempt events.")
    +      null
    +    }
    +
    +    def completeTransaction(sequenceNumber: CharSequence, success: Boolean) {
    +      val processorOpt = Option(processorMap.remove(sequenceNumber))
    +      if (processorOpt.isDefined) {
    +        val processor = processorOpt.get
    +        processor.resultQueueUpdateLock.lock()
    +        try {
    +          // Is the sequence number the same as the one the processor is processing? If not,
    +          // don't update {
    +          if (processor.eventBatch.getSequenceNumber.equals(sequenceNumber)) {
    +            processor.resultQueue.put(success)
    +          }
    +        } finally {
    +          processor.resultQueueUpdateLock.unlock()
    +        }
    +      }
    +    }
    +  }
    +
    +  // Flume forces transactions to be thread-local (horrible, I know!)
    +  // So the sink basically spawns a new thread to pull the events out within a transaction.
    +  // The thread fills in the event batch object that is set before the thread is scheduled.
    +  // After filling it in, the thread waits on a condition - which is released only
    +  // when the success message comes back for the specific sequence number for that event batch.
    +  /**
    +   * This class represents a transaction on the Flume channel. This class runs a separate thread
    +   * which owns the transaction. It is blocked until the success call for that transaction comes
    +   * back.
    +   * @param maxBatchSize
    +   */
    +  private class TransactionProcessor(var maxBatchSize: Int) extends Callable[Void] {
    +    // Must be set to a new event batch before scheduling this!!
    +    val eventBatch = new EventBatch("", new util.LinkedList[SparkSinkEvent])
    +    val eventQueue = new SynchronousQueue[EventBatch]()
    +    val resultQueue = new SynchronousQueue[Boolean]()
    +    val resultQueueUpdateLock = new ReentrantLock()
    +
    +    object Zero {
    +      val zero = "0" // Oh, I miss static finals
    +    }
    +
    +
    +    override def call(): Void = {
    +      val tx = getChannel.getTransaction
    +      tx.begin()
    +      try {
    +        eventBatch.setSequenceNumber(seqBase + seqNum.incrementAndGet())
    +        val events = eventBatch.getEventBatch
    +        events.clear()
    +        val loop = new Breaks
    +        var gotEventsInThisTxn = false
    +        loop.breakable {
    +          var i = 0
    +          // Using for here causes the maxBatchSize change to be ineffective as the Range gets
    +          // pregenerated
    +          while (i < maxBatchSize) {
    +            i += 1
    +            val eventOpt = Option(getChannel.take())
    +            eventOpt.map(event => {
    +              events.add(new SparkSinkEvent(toCharSequenceMap(event
    +                .getHeaders),
    +                ByteBuffer.wrap(event.getBody)))
    +              gotEventsInThisTxn = true
    +            })
    +            if (eventOpt.isEmpty) {
    +              if (!gotEventsInThisTxn) {
    +                // To avoid sending empty batches, we wait till events are available backing off
    +                // between attempts to get events. Each attempt to get an event though causes one
    +                // iteration to be lost. To ensure that we still send back maxBatchSize number of
    +                // events, we cheat and increase the maxBatchSize by 1 to account for the lost
    +                // iteration. Even throwing an exception is expensive as Avro will serialize it
    +                // and send it over the wire, which is useless. Before incrementing though,
    +                // ensure that we are not anywhere near INT_MAX.
    +                if (maxBatchSize >= Int.MaxValue / 2) {
    +                  // Random sanity check
    +                  throw new RuntimeException("Safety exception - polled too many times, no events!")
    +                }
    +                maxBatchSize += 1
    +                Thread.sleep(500)
    +              } else {
    +                loop.break()
    +              }
    +            }
    +          }
    +        }
    +        // Make the data available to the sender thread
    +        eventQueue.put(eventBatch)
    +
    +        // Wait till timeout for the ack/nack
    +        val maybeResult = Option(resultQueue.poll(transactionTimeout, TimeUnit.SECONDS))
    +        // There is a race condition here.
    +        // 1. This times out.
    +        // 2. The result is empty, so timeout exception is thrown.
    +        // 3. The ack comes in before the finally block is entered
    +        // 4. The thread with the ack has a handle to this processor,
    +        // and another thread has the same processor checked out
    +        // (since the finally block was executed and the processor checked back in)
    +        // 5. The thread with the ack now updates the result queue,
    +        // so the processor thinks it is the ack for the current batch.
    +        // To avoid this - update the sequence number to "0" (with or without a result - does not
    +        // matter).
    +        // In the ack method, check if the seq number is the same as the processor's -
    +        // if they are then update the result queue. Now if the
    +        // processor updates the seq number first - the ack/nack never updates the result. If the
    +        // ack/nack updates the
    +        // result after the timeout but before the seq number is updated to "0" it does not
    +        // matter - the processor would
    +        // still timeout and the result is cleared before reusing the processor.
    +        // Unfortunately, this needs to be done from within a lock
    +        // to make sure that the new sequence number is actually visible to the ack thread
    +        // (happens-before)
    +        resultQueueUpdateLock.lock()
    +        try {
    +          eventBatch.setSequenceNumber(Zero.zero)
    +        } finally {
    +          resultQueueUpdateLock.unlock()
    +        }
    +        eventBatch.getEventBatch.clear()
    +        // If the batch failed on spark side, throw a FlumeException
    +        maybeResult.map(success =>
    +          if (!success) {
    +            throw new
    +                FlumeException("Spark could not accept events. The transaction will be retried.")
    +          }
    +        )
    +        // If the operation timed out, throw a TimeoutException
    +        if (maybeResult.isEmpty) {
    +          throw new TimeoutException("Spark did not respond within the timeout period of " +
    +            transactionTimeout + "seconds. Transaction will be retried")
    +        }
    +        null
    +      } catch {
    +        case e: Throwable =>
    +          try {
    +            LOG.warn("Error while attempting to remove events from the channel.", e)
    +            tx.rollback()
    +          } catch {
    +            case e1: Throwable => LOG.error(
    +              "Rollback failed while attempting to rollback due to commit failure.", e1)
    +          }
    +          null // No point rethrowing the exception
    +      } finally {
    +        // Must *always* release the caller thread
    +        eventQueue.put(ErrorEventBatch)
    +        // In the case of success coming after the timeout, but before resetting the seq number
    +        // remove the event from the map and then clear the value
    +        resultQueue.clear()
    +        processorMap.remove(eventBatch.getSequenceNumber)
    +        processorFactory.get.checkIn(this)
    +        tx.close()
    +      }
    +    }
    +
    +    def toCharSequenceMap(inMap: java.util.Map[String, String]): java.util.Map[CharSequence,
    +      CharSequence] = {
    +      val charSeqMap = new util.HashMap[CharSequence, CharSequence](inMap.size())
    +      charSeqMap.putAll(inMap)
    +      charSeqMap
    +    }
    +  }
    +
    +  private class SparkHandlerFactory(val maxInstances: Int) {
    +    val queue = new scala.collection.mutable.Queue[TransactionProcessor]
    +    val queueModificationLock = new ReentrantLock()
    +    var currentSize = 0
    +    val waitForCheckIn = queueModificationLock.newCondition()
    +
    +    def checkOut(n: Int): TransactionProcessor = {
    +      def getProcessor = {
    +        val processor = queue.dequeue()
    +        processor.maxBatchSize = n
    +        processor
    +      }
    +      queueModificationLock.lock()
    +      try {
    +        if (queue.size > 0) {
    +          getProcessor
    +        }
    +        else {
    +          if (currentSize < maxInstances) {
    +            currentSize += 1
    --- End diff --
    
    So isnt `currentSize` same as `queue.size` ? Why need a separate variable?


---
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 infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] spark pull request: SPARK-1729. Make Flume pull data from source, ...

Posted by harishreedharan <gi...@git.apache.org>.
Github user harishreedharan commented on a diff in the pull request:

    https://github.com/apache/spark/pull/807#discussion_r13477246
  
    --- Diff: external/flume-sink/src/main/scala/org/apache/spark/flume/sink/SparkSink.scala ---
    @@ -0,0 +1,392 @@
    +/*
    + * 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.flume.sink
    +
    +import org.apache.flume.sink.AbstractSink
    +import java.util.concurrent.locks.ReentrantLock
    +import org.apache.flume.Sink.Status
    +import org.apache.spark.flume.{SparkSinkEvent, EventBatch, SparkFlumeProtocol}
    +import scala.util.control.Breaks
    +import java.nio.ByteBuffer
    +import org.apache.flume.{FlumeException, Context}
    +import org.slf4j.LoggerFactory
    +import java.util.concurrent.atomic.AtomicLong
    +import org.apache.commons.lang.RandomStringUtils
    +import java.util.concurrent._
    +import java.util
    +import org.apache.flume.conf.{ConfigurationException, Configurable}
    +import com.google.common.util.concurrent.ThreadFactoryBuilder
    +import org.apache.avro.ipc.NettyServer
    +import org.apache.avro.ipc.specific.SpecificResponder
    +import java.net.InetSocketAddress
    +
    +class SparkSink() extends AbstractSink with Configurable {
    +  private val LOG = LoggerFactory.getLogger(this.getClass)
    +  private val lock = new ReentrantLock()
    +  private val blockingCondition = lock.newCondition()
    +
    +  // This sink will not persist sequence numbers and reuses them if it gets restarted.
    +  // So it is possible to commit a transaction which may have been meant for the sink before the
    +  // restart.
    +  // Since the new txn may not have the same sequence number we must guard against accidentally
    +  // committing
    +  // a new transaction. To reduce the probability of that happening a random string is prepended
    +  // to the sequence number.
    +  // Does not change for life of sink
    +  private val seqBase = RandomStringUtils.randomAlphanumeric(8)
    +  // Incremented for each transaction
    +  private val seqNum = new AtomicLong(0)
    +
    +  private var transactionExecutorOpt: Option[ExecutorService] = None
    +
    +  private var numProcessors: Integer = SparkSinkConfig.DEFAULT_PROCESSOR_COUNT
    +  private var transactionTimeout = SparkSinkConfig.DEFAULT_TRANSACTION_TIMEOUT
    +
    +  private val processorMap = new ConcurrentHashMap[CharSequence, TransactionProcessor]()
    +
    +  private var processorFactory: Option[SparkHandlerFactory] = None
    +  private var hostname: String = SparkSinkConfig.DEFAULT_HOSTNAME
    +  private var port: Int = 0
    +  private var maxThreads: Int = SparkSinkConfig.DEFAULT_MAX_THREADS
    +  private var serverOpt: Option[NettyServer] = None
    +  private var running = false
    +
    +  override def start() {
    +    transactionExecutorOpt = Option(Executors.newFixedThreadPool(numProcessors,
    +      new ThreadFactoryBuilder().setDaemon(true)
    +        .setNameFormat("Spark Sink, " + getName + " Processor Thread - %d").build()))
    +
    +    processorFactory = Option(new SparkHandlerFactory(numProcessors))
    +
    +    val responder = new SpecificResponder(classOf[SparkFlumeProtocol], new AvroCallbackHandler())
    +
    +    // Using the constructor that takes specific thread-pools requires bringing in netty
    +    // dependencies which are being excluded in the build. In practice,
    +    // Netty dependencies are already available on the JVM as Flume would have pulled them in.
    +    serverOpt = Option(new NettyServer(responder, new InetSocketAddress(hostname, port)))
    +
    +    serverOpt.map(server => server.start())
    +    lock.lock()
    +    try {
    +      running = true
    +    } finally {
    +      lock.unlock()
    +    }
    +    super.start()
    +  }
    +
    +  override def stop() {
    +    transactionExecutorOpt.map(executor => executor.shutdownNow())
    +    serverOpt.map(server => {
    +      server.close()
    +      server.join()
    +    })
    +    lock.lock()
    +    try {
    +      running = false
    +      blockingCondition.signalAll()
    +    } finally {
    +      lock.unlock()
    +    }
    +  }
    +
    +  override def configure(ctx: Context) {
    +    import SparkSinkConfig._
    +    hostname = ctx.getString(CONF_HOSTNAME, DEFAULT_HOSTNAME)
    +    val portOpt = Option(ctx.getInteger(CONF_PORT))
    +    if(portOpt.isDefined) {
    +      port = portOpt.get
    +    } else {
    +      throw new ConfigurationException("The Port to bind must be specified")
    +    }
    +    numProcessors = ctx.getInteger(PROCESSOR_COUNT, DEFAULT_PROCESSOR_COUNT)
    +    transactionTimeout = ctx.getInteger(CONF_TRANSACTION_TIMEOUT, DEFAULT_TRANSACTION_TIMEOUT)
    +    maxThreads = ctx.getInteger(CONF_MAX_THREADS, DEFAULT_MAX_THREADS)
    +  }
    +
    +  override def process(): Status = {
    +    // This method is called in a loop by the Flume framework - block it until the sink is
    +    // stopped to save CPU resources
    +    lock.lock()
    +    try {
    +      while(running) {
    +        blockingCondition.await()
    +      }
    +    } finally {
    +      lock.unlock()
    +    }
    +    Status.BACKOFF
    +  }
    +
    +
    +  // Object representing an empty batch returned by the txn processor due to some error.
    +  case object ErrorEventBatch extends EventBatch
    +
    +  private class AvroCallbackHandler() extends SparkFlumeProtocol {
    +
    +    override def getEventBatch(n: Int): EventBatch = {
    +      val processor = processorFactory.get.checkOut(n)
    +      transactionExecutorOpt.map(executor => executor.submit(processor))
    +      // Wait until a batch is available - can be null if some error was thrown
    +      val eventBatch = processor.eventQueue.take()
    +      eventBatch match {
    +        case ErrorEventBatch => throw new FlumeException("Something went wrong. No events" +
    +          " retrieved from channel.")
    +        case events => {
    +          processorMap.put(events.getSequenceNumber, processor)
    +          if (LOG.isDebugEnabled) {
    +            LOG.debug("Sent " + events.getEventBatch.size() +
    +              " events with sequence number: " + events.getSequenceNumber)
    +          }
    +          events
    +        }
    +      }
    +    }
    +
    +    override def ack(sequenceNumber: CharSequence): Void = {
    +      completeTransaction(sequenceNumber, success = true)
    +      null
    +    }
    +
    +    override def nack(sequenceNumber: CharSequence): Void = {
    +      completeTransaction(sequenceNumber, success = false)
    +      LOG.info("Spark failed to commit transaction. Will reattempt events.")
    +      null
    +    }
    +
    +    def completeTransaction(sequenceNumber: CharSequence, success: Boolean) {
    +      val processorOpt = Option(processorMap.remove(sequenceNumber))
    +      if (processorOpt.isDefined) {
    +        val processor = processorOpt.get
    +        processor.resultQueueUpdateLock.lock()
    +        try {
    +          // Is the sequence number the same as the one the processor is processing? If not,
    +          // don't update {
    +          if (processor.eventBatch.getSequenceNumber.equals(sequenceNumber)) {
    +            processor.resultQueue.put(success)
    +          }
    +        } finally {
    +          processor.resultQueueUpdateLock.unlock()
    +        }
    +      }
    +    }
    +  }
    +
    +  // Flume forces transactions to be thread-local (horrible, I know!)
    +  // So the sink basically spawns a new thread to pull the events out within a transaction.
    +  // The thread fills in the event batch object that is set before the thread is scheduled.
    +  // After filling it in, the thread waits on a condition - which is released only
    +  // when the success message comes back for the specific sequence number for that event batch.
    +  /**
    +   * This class represents a transaction on the Flume channel. This class runs a separate thread
    +   * which owns the transaction. It is blocked until the success call for that transaction comes
    +   * back.
    +   * @param maxBatchSize
    +   */
    +  private class TransactionProcessor(var maxBatchSize: Int) extends Callable[Void] {
    +    // Must be set to a new event batch before scheduling this!!
    +    val eventBatch = new EventBatch("", new util.LinkedList[SparkSinkEvent])
    +    val eventQueue = new SynchronousQueue[EventBatch]()
    +    val resultQueue = new SynchronousQueue[Boolean]()
    +    val resultQueueUpdateLock = new ReentrantLock()
    +
    +    object Zero {
    +      val zero = "0" // Oh, I miss static finals
    +    }
    +
    +
    +    override def call(): Void = {
    +      val tx = getChannel.getTransaction
    +      tx.begin()
    +      try {
    +        eventBatch.setSequenceNumber(seqBase + seqNum.incrementAndGet())
    +        val events = eventBatch.getEventBatch
    +        events.clear()
    +        val loop = new Breaks
    +        var gotEventsInThisTxn = false
    +        loop.breakable {
    +          var i = 0
    +          // Using for here causes the maxBatchSize change to be ineffective as the Range gets
    +          // pregenerated
    +          while (i < maxBatchSize) {
    +            i += 1
    +            val eventOpt = Option(getChannel.take())
    +            eventOpt.map(event => {
    +              events.add(new SparkSinkEvent(toCharSequenceMap(event
    +                .getHeaders),
    +                ByteBuffer.wrap(event.getBody)))
    +              gotEventsInThisTxn = true
    +            })
    +            if (eventOpt.isEmpty) {
    +              if (!gotEventsInThisTxn) {
    +                // To avoid sending empty batches, we wait till events are available backing off
    +                // between attempts to get events. Each attempt to get an event though causes one
    +                // iteration to be lost. To ensure that we still send back maxBatchSize number of
    +                // events, we cheat and increase the maxBatchSize by 1 to account for the lost
    +                // iteration. Even throwing an exception is expensive as Avro will serialize it
    +                // and send it over the wire, which is useless. Before incrementing though,
    +                // ensure that we are not anywhere near INT_MAX.
    +                if (maxBatchSize >= Int.MaxValue / 2) {
    +                  // Random sanity check
    +                  throw new RuntimeException("Safety exception - polled too many times, no events!")
    +                }
    +                maxBatchSize += 1
    +                Thread.sleep(500)
    +              } else {
    +                loop.break()
    +              }
    +            }
    +          }
    +        }
    +        // Make the data available to the sender thread
    +        eventQueue.put(eventBatch)
    +
    +        // Wait till timeout for the ack/nack
    +        val maybeResult = Option(resultQueue.poll(transactionTimeout, TimeUnit.SECONDS))
    +        // There is a race condition here.
    +        // 1. This times out.
    +        // 2. The result is empty, so timeout exception is thrown.
    +        // 3. The ack comes in before the finally block is entered
    +        // 4. The thread with the ack has a handle to this processor,
    +        // and another thread has the same processor checked out
    +        // (since the finally block was executed and the processor checked back in)
    +        // 5. The thread with the ack now updates the result queue,
    +        // so the processor thinks it is the ack for the current batch.
    +        // To avoid this - update the sequence number to "0" (with or without a result - does not
    +        // matter).
    +        // In the ack method, check if the seq number is the same as the processor's -
    +        // if they are then update the result queue. Now if the
    +        // processor updates the seq number first - the ack/nack never updates the result. If the
    +        // ack/nack updates the
    +        // result after the timeout but before the seq number is updated to "0" it does not
    +        // matter - the processor would
    +        // still timeout and the result is cleared before reusing the processor.
    +        // Unfortunately, this needs to be done from within a lock
    +        // to make sure that the new sequence number is actually visible to the ack thread
    +        // (happens-before)
    +        resultQueueUpdateLock.lock()
    +        try {
    +          eventBatch.setSequenceNumber(Zero.zero)
    +        } finally {
    +          resultQueueUpdateLock.unlock()
    +        }
    +        eventBatch.getEventBatch.clear()
    +        // If the batch failed on spark side, throw a FlumeException
    +        maybeResult.map(success =>
    +          if (!success) {
    +            throw new
    +                FlumeException("Spark could not accept events. The transaction will be retried.")
    +          }
    +        )
    +        // If the operation timed out, throw a TimeoutException
    +        if (maybeResult.isEmpty) {
    +          throw new TimeoutException("Spark did not respond within the timeout period of " +
    +            transactionTimeout + "seconds. Transaction will be retried")
    +        }
    +        null
    +      } catch {
    +        case e: Throwable =>
    +          try {
    +            LOG.warn("Error while attempting to remove events from the channel.", e)
    +            tx.rollback()
    +          } catch {
    +            case e1: Throwable => LOG.error(
    +              "Rollback failed while attempting to rollback due to commit failure.", e1)
    +          }
    +          null // No point rethrowing the exception
    +      } finally {
    +        // Must *always* release the caller thread
    +        eventQueue.put(ErrorEventBatch)
    +        // In the case of success coming after the timeout, but before resetting the seq number
    +        // remove the event from the map and then clear the value
    +        resultQueue.clear()
    +        processorMap.remove(eventBatch.getSequenceNumber)
    +        processorFactory.get.checkIn(this)
    +        tx.close()
    +      }
    +    }
    +
    +    def toCharSequenceMap(inMap: java.util.Map[String, String]): java.util.Map[CharSequence,
    +      CharSequence] = {
    +      val charSeqMap = new util.HashMap[CharSequence, CharSequence](inMap.size())
    +      charSeqMap.putAll(inMap)
    +      charSeqMap
    +    }
    +  }
    +
    +  private class SparkHandlerFactory(val maxInstances: Int) {
    +    val queue = new scala.collection.mutable.Queue[TransactionProcessor]
    +    val queueModificationLock = new ReentrantLock()
    +    var currentSize = 0
    +    val waitForCheckIn = queueModificationLock.newCondition()
    +
    +    def checkOut(n: Int): TransactionProcessor = {
    +      def getProcessor = {
    +        val processor = queue.dequeue()
    +        processor.maxBatchSize = n
    +        processor
    +      }
    +      queueModificationLock.lock()
    +      try {
    +        if (queue.size > 0) {
    +          getProcessor
    +        }
    +        else {
    +          if (currentSize < maxInstances) {
    +            currentSize += 1
    +            new TransactionProcessor(n)
    +          } else {
    +            // No events in queue and cannot initialize more!
    +            // Since currentSize never reduces, queue size increasing is the only hope
    +            while (queue.size == 0 && currentSize >= maxInstances) {
    +              waitForCheckIn.await()
    +            }
    +            getProcessor
    +          }
    +        }
    +      } finally {
    +        queueModificationLock.unlock()
    +      }
    +    }
    +
    +    def checkIn(processor: TransactionProcessor) {
    +      queueModificationLock.lock()
    --- End diff --
    
    Looks like we'd still need a lock, since we have to do a set of ops atomically (check if the queue has anything, then pop else check that currentSize < maxInstances and create a new instance - all this needs to be done atomically, else it is possible that sizes can grow beyond maxInstances).  Using a blocking queue that way would end up being more expensive.


---
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 infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] spark pull request: SPARK-1729. Make Flume pull data from source, ...

Posted by tdas <gi...@git.apache.org>.
Github user tdas commented on a diff in the pull request:

    https://github.com/apache/spark/pull/807#discussion_r13833907
  
    --- Diff: external/flume-sink/src/main/scala/org/apache/spark/flume/sink/SparkSink.scala ---
    @@ -0,0 +1,432 @@
    +/*
    + * 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.flume.sink
    +
    +import java.net.InetSocketAddress
    +import java.nio.ByteBuffer
    +import java.util
    +import java.util.concurrent._
    +import java.util.concurrent.atomic.AtomicLong
    +
    +import scala.util.control.Breaks
    +
    +import com.google.common.util.concurrent.ThreadFactoryBuilder
    +import org.apache.avro.ipc.NettyServer
    +import org.apache.avro.ipc.specific.SpecificResponder
    +import org.apache.commons.lang.RandomStringUtils
    +import org.apache.flume.Sink.Status
    +import org.apache.flume.conf.{ConfigurationException, Configurable}
    +import org.apache.flume.sink.AbstractSink
    +import org.apache.flume.{Channel, Transaction, FlumeException, Context}
    +import org.slf4j.LoggerFactory
    +
    +import org.apache.spark.flume.{SparkSinkEvent, EventBatch, SparkFlumeProtocol}
    +
    +/**
    + * A sink that uses Avro RPC to run a server that can be polled by Spark's
    + * FlumePollingInputDStream. This sink has the following configuration parameters:
    + *
    + * hostname - The hostname to bind to. Default: 0.0.0.0
    + * port - The port to bind to. (No default - mandatory)
    + * timeout - Time in seconds after which a transaction is rolled back,
    + * if an ACK is not received from Spark within that time
    + * threads - Number of threads to use to receive requests from Spark (Default: 10)
    + *
    + */
    +// Flume forces transactions to be thread-local. So each transaction *must* be committed, or
    +// rolled back from the thread it was originally created in. So each getEvents call from Spark
    +// creates a TransactionProcessor which runs in a new thread, in which the transaction is created
    +// and events are pulled off the channel. Once the events are sent to spark,
    +// that thread is blocked and the TransactionProcessor is saved in a map,
    +// until an ACK or NACK comes back or the transaction times out (after the specified timeout).
    +// When the response comes, the TransactionProcessor is retrieved and then unblocked,
    +// at which point the transaction is committed or rolled back.
    +class SparkSink extends AbstractSink with Configurable {
    +
    +  // Size of the pool to use for holding transaction processors.
    +  private var poolSize: Integer = SparkSinkConfig.DEFAULT_THREADS
    +
    +  // Timeout for each transaction. If spark does not respond in this much time,
    +  // rollback the transaction
    +  private var transactionTimeout = SparkSinkConfig.DEFAULT_TRANSACTION_TIMEOUT
    +
    +  // Address info to bind on
    +  private var hostname: String = SparkSinkConfig.DEFAULT_HOSTNAME
    +  private var port: Int = 0
    +
    +  // Handle to the server
    +  private var serverOpt: Option[NettyServer] = None
    +
    +  // The handler that handles the callback from Avro
    +  private var handler: Option[SparkAvroCallbackHandler] = None
    +
    +  // Latch that blocks off the Flume framework from wasting 1 thread.
    +  private val blockingLatch = new CountDownLatch(1)
    +
    +  override def start() {
    +    handler = Option(new SparkAvroCallbackHandler(poolSize, getChannel, transactionTimeout))
    +    val responder = new SpecificResponder(classOf[SparkFlumeProtocol], handler.get)
    +    // Using the constructor that takes specific thread-pools requires bringing in netty
    +    // dependencies which are being excluded in the build. In practice,
    +    // Netty dependencies are already available on the JVM as Flume would have pulled them in.
    +    serverOpt = Option(new NettyServer(responder, new InetSocketAddress(hostname, port)))
    +    serverOpt.map(server => {
    +      server.start()
    +    })
    +    super.start()
    +  }
    +
    +  override def stop() {
    +    handler.map(callbackHandler => {
    +      callbackHandler.shutdown()
    +    })
    +    serverOpt.map(server => {
    +      server.close()
    +      server.join()
    +    })
    +    blockingLatch.countDown()
    +    super.stop()
    +  }
    +
    +  /**
    +   * @param ctx
    +   */
    +  override def configure(ctx: Context) {
    +    import SparkSinkConfig._
    +    hostname = ctx.getString(CONF_HOSTNAME, DEFAULT_HOSTNAME)
    +    port = Option(ctx.getInteger(CONF_PORT)).
    +      getOrElse(throw new ConfigurationException("The port to bind to must be specified"))
    +    poolSize = ctx.getInteger(THREADS, DEFAULT_THREADS)
    +    transactionTimeout = ctx.getInteger(CONF_TRANSACTION_TIMEOUT, DEFAULT_TRANSACTION_TIMEOUT)
    +  }
    +
    +  override def process(): Status = {
    +    // This method is called in a loop by the Flume framework - block it until the sink is
    +    // stopped to save CPU resources. The sink runner will interrupt this thread when the sink is
    +    // being shut down.
    +    blockingLatch.await()
    +    Status.BACKOFF
    +  }
    +}
    +
    +/**
    + * Class that implements the SparkFlumeProtocol, that is used by the Avro Netty Server to process
    + * requests. Each getEvents, ack and nack call is forwarded to an instance of this class.
    + * @param threads Number of threads to use to process requests.
    + * @param channel The channel that the sink pulls events from
    + * @param transactionTimeout Timeout in millis after which the transaction if not acked by Spark
    + *                           is rolled back.
    + */
    +private class SparkAvroCallbackHandler(val threads: Int, val channel: Channel,
    +  val transactionTimeout: Int) extends SparkFlumeProtocol {
    +  private val LOG = LoggerFactory.getLogger(classOf[SparkAvroCallbackHandler])
    +  val transactionExecutorOpt = Option(Executors.newFixedThreadPool(threads,
    +    new ThreadFactoryBuilder().setDaemon(true)
    +      .setNameFormat("Spark Sink Processor Thread - %d").build()))
    +  private val processorMap = new ConcurrentHashMap[CharSequence, TransactionProcessor]()
    +  // This sink will not persist sequence numbers and reuses them if it gets restarted.
    +  // So it is possible to commit a transaction which may have been meant for the sink before the
    +  // restart.
    +  // Since the new txn may not have the same sequence number we must guard against accidentally
    +  // committing a new transaction. To reduce the probability of that happening a random string is
    +  // prepended to the sequence number. Does not change for life of sink
    +  private val seqBase = RandomStringUtils.randomAlphanumeric(8)
    +  private val seqCounter = new AtomicLong(0)
    +
    +  /**
    +   * Returns a bunch of events to Spark over Avro RPC.
    +   * @param n Maximum number of events to return in a batch
    +   * @return [[EventBatch]] instance that has a sequence number and an array of at most n events
    +   */
    +  override def getEventBatch(n: Int): EventBatch = {
    +    val sequenceNumber = seqBase + seqCounter.incrementAndGet()
    +    val processor = new TransactionProcessor(channel, sequenceNumber,
    +      n, transactionTimeout, this)
    +    transactionExecutorOpt.map(executor => {
    +      executor.submit(processor)
    +    })
    +    // Wait until a batch is available - can be null if some error was thrown
    +    processor.getEventBatch match {
    +      case ErrorEventBatch => throw new FlumeException("Something went wrong. No events" +
    +        " retrieved from channel.")
    +      case eventBatch: EventBatch =>
    +        processorMap.put(sequenceNumber, processor)
    +        if (LOG.isDebugEnabled()) {
    +          LOG.debug("Sent " + eventBatch.getEvents.size() +
    +            " events with sequence number: " + eventBatch.getSequenceNumber)
    +        }
    +        eventBatch
    +    }
    +  }
    +
    +  /**
    +   * Called by Spark to indicate successful commit of a batch
    +   * @param sequenceNumber The sequence number of the event batch that was successful
    +   */
    +  override def ack(sequenceNumber: CharSequence): Void = {
    +    completeTransaction(sequenceNumber, success = true)
    +    null
    +  }
    +
    +  /**
    +   * Called by Spark to indicate failed commit of a batch
    +   * @param sequenceNumber The sequence number of the event batch that failed
    +   * @return
    +   */
    +  override def nack(sequenceNumber: CharSequence): Void = {
    +    completeTransaction(sequenceNumber, success = false)
    +    LOG.info("Spark failed to commit transaction. Will reattempt events.")
    +    null
    +  }
    +
    +  /**
    +   * Helper method to commit or rollback a transaction.
    +   * @param sequenceNumber The sequence number of the batch that was completed
    +   * @param success Whether the batch was successful or not.
    +   */
    +  private def completeTransaction(sequenceNumber: CharSequence, success: Boolean) {
    +    Option(removeAndGetProcessor(sequenceNumber)).map(processor => {
    +      processor.batchProcessed(success)
    +    })
    +  }
    +
    +  /**
    +   * Helper method to remove the TxnProcessor for a Sequence Number. Can be used to avoid a leak.
    +   * @param sequenceNumber
    +   * @return The transaction processor for the corresponding batch. Note that this instance is no
    +   *         longer tracked and the caller is responsible for that txn processor.
    +   */
    +  private[flume] def removeAndGetProcessor(sequenceNumber: CharSequence): TransactionProcessor = {
    +    processorMap.remove(sequenceNumber.toString) // The toString is required!
    +  }
    +
    +  /**
    +   * Shuts down the executor used to process transactions.
    +   */
    +  def shutdown() {
    +    transactionExecutorOpt.map(executor => {
    +      executor.shutdownNow()
    +    })
    +  }
    +}
    +
    +/**
    + * Object representing an empty batch returned by the txn processor due to some error.
    + */
    +case object ErrorEventBatch extends EventBatch
    +
    +// Flume forces transactions to be thread-local (horrible, I know!)
    +// So the sink basically spawns a new thread to pull the events out within a transaction.
    +// The thread fills in the event batch object that is set before the thread is scheduled.
    +// After filling it in, the thread waits on a condition - which is released only
    +// when the success message comes back for the specific sequence number for that event batch.
    +/**
    + * This class represents a transaction on the Flume channel. This class runs a separate thread
    + * which owns the transaction. The thread is blocked until the success call for that transaction
    + * comes back with an ACK or NACK.
    + * @param channel The channel from which to pull events
    + * @param seqNum The sequence number to use for the transaction. Must be unique
    + * @param maxBatchSize The maximum number of events to process per batch
    + * @param transactionTimeout Time in seconds after which a transaction must be rolled back
    + *                           without waiting for an ACK from Spark
    + * @param parent The parent [[SparkAvroCallbackHandler]] instance, for reporting timeouts
    + */
    +private class TransactionProcessor(val channel: Channel, val seqNum: String,
    +  var maxBatchSize: Int, val transactionTimeout: Int,
    +  val parent: SparkAvroCallbackHandler) extends Callable[Void] {
    +
    +  private val LOG = LoggerFactory.getLogger(classOf[TransactionProcessor])
    +
    +  // If a real batch is not returned, we always have to return an error batch.
    +  @volatile private var eventBatch: EventBatch = ErrorEventBatch
    +
    +  // Synchronization primitives
    +  val batchGeneratedLatch = new CountDownLatch(1)
    +  val batchAckLatch = new CountDownLatch(1)
    +
    +  // Sanity check to ensure we don't loop like crazy
    +  val totalAttemptsToRemoveFromChannel = Int.MaxValue / 2
    +
    +  // OK to use volatile, since the change would only make this true (otherwise it will be
    +  // changed to false - we never apply a negation operation to this) - which means the transaction
    +  // succeeded.
    +  @volatile private var batchSuccess = false
    +
    +  // The transaction that this processor would handle
    +  var txOpt: Option[Transaction] = None
    +
    +  /**
    +   * Get an event batch from the channel. This method will block until a batch of events is
    +   * available from the channel. If no events are available after a large number of attempts of
    +   * polling the channel, this method will return [[ErrorEventBatch]].
    +   *
    +   * @return An [[EventBatch]] instance with sequence number set to [[seqNum]], filled with a
    +   *         maximum of [[maxBatchSize]] events
    +   */
    +  def getEventBatch: EventBatch = {
    +    batchGeneratedLatch.await()
    +    eventBatch
    +  }
    +
    +  /**
    +   * This method is to be called by the sink when it receives an ACK or NACK from Spark. This
    +   * method is a no-op if it is called after [[transactionTimeout]] has expired since
    +   * [[getEventBatch]] returned a batch of events.
    +   * @param success True if an ACK was received and the transaction should be committed, else false.
    +   */
    +  def batchProcessed(success: Boolean) {
    +    if (LOG.isDebugEnabled) {
    +      LOG.debug("Batch processed for sequence number: " + seqNum)
    +    }
    +    batchSuccess = success
    +    batchAckLatch.countDown()
    +  }
    +
    +  /**
    +   * Populates events into the event batch. If the batch cannot be populated,
    +   * this method will not set the event batch which will stay [[ErrorEventBatch]]
    +   */
    +  private def populateEvents() {
    +    try {
    +      txOpt = Option(channel.getTransaction)
    +      txOpt.map(tx => {
    +        tx.begin()
    +        val events = new util.ArrayList[SparkSinkEvent](maxBatchSize)
    +        val loop = new Breaks
    +        var gotEventsInThisTxn = false
    +        var loopCounter: Int = 0
    +        loop.breakable {
    +          while (events.size() < maxBatchSize
    +            && loopCounter < totalAttemptsToRemoveFromChannel) {
    +            loopCounter += 1
    +            Option(channel.take()) match {
    +              case Some(event) =>
    +                events.add(new SparkSinkEvent(toCharSequenceMap(event.getHeaders),
    +                  ByteBuffer.wrap(event.getBody)))
    +                gotEventsInThisTxn = true
    +              case None =>
    +                if (!gotEventsInThisTxn) {
    +                  TimeUnit.MILLISECONDS.sleep(500)
    +                } else {
    +                  loop.break()
    +                }
    +            }
    +          }
    +        }
    +        if (!gotEventsInThisTxn) {
    +          throw new FlumeException("Tried too many times, didn't get any events from the channel")
    +        }
    +        // At this point, the events are available, so fill them into the event batch
    +        eventBatch = new EventBatch(seqNum, events)
    +      })
    +    } catch {
    +      case e: Throwable =>
    +        LOG.error("Error while processing transaction.", e)
    +        try {
    +          txOpt.map(tx => {
    +            rollbackAndClose(tx, close = true)
    +          })
    +        } finally {
    +          // Avro might serialize the exception and cause a NACK,
    +          // so don't bother with the transaction
    +          txOpt = None
    +        }
    +    } finally {
    +      batchGeneratedLatch.countDown()
    +    }
    +  }
    +
    +  /**
    +   * Waits for upto [[transactionTimeout]] seconds for an ACK. If an ACK comes in,
    --- End diff --
    
    Nit: `[[ ]]` is used only to refer to library class. Not a field. :)


---
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 infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] spark pull request: SPARK-1729. Make Flume pull data from source, ...

Posted by tdas <gi...@git.apache.org>.
Github user tdas commented on a diff in the pull request:

    https://github.com/apache/spark/pull/807#discussion_r13473209
  
    --- Diff: external/flume-sink/src/main/scala/org/apache/spark/flume/sink/SparkSink.scala ---
    @@ -0,0 +1,392 @@
    +/*
    + * 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.flume.sink
    +
    +import org.apache.flume.sink.AbstractSink
    +import java.util.concurrent.locks.ReentrantLock
    +import org.apache.flume.Sink.Status
    +import org.apache.spark.flume.{SparkSinkEvent, EventBatch, SparkFlumeProtocol}
    +import scala.util.control.Breaks
    +import java.nio.ByteBuffer
    +import org.apache.flume.{FlumeException, Context}
    +import org.slf4j.LoggerFactory
    +import java.util.concurrent.atomic.AtomicLong
    +import org.apache.commons.lang.RandomStringUtils
    +import java.util.concurrent._
    +import java.util
    +import org.apache.flume.conf.{ConfigurationException, Configurable}
    +import com.google.common.util.concurrent.ThreadFactoryBuilder
    +import org.apache.avro.ipc.NettyServer
    +import org.apache.avro.ipc.specific.SpecificResponder
    +import java.net.InetSocketAddress
    +
    +class SparkSink() extends AbstractSink with Configurable {
    +  private val LOG = LoggerFactory.getLogger(this.getClass)
    +  private val lock = new ReentrantLock()
    +  private val blockingCondition = lock.newCondition()
    +
    +  // This sink will not persist sequence numbers and reuses them if it gets restarted.
    +  // So it is possible to commit a transaction which may have been meant for the sink before the
    +  // restart.
    +  // Since the new txn may not have the same sequence number we must guard against accidentally
    +  // committing
    +  // a new transaction. To reduce the probability of that happening a random string is prepended
    +  // to the sequence number.
    +  // Does not change for life of sink
    +  private val seqBase = RandomStringUtils.randomAlphanumeric(8)
    +  // Incremented for each transaction
    +  private val seqNum = new AtomicLong(0)
    +
    +  private var transactionExecutorOpt: Option[ExecutorService] = None
    +
    +  private var numProcessors: Integer = SparkSinkConfig.DEFAULT_PROCESSOR_COUNT
    +  private var transactionTimeout = SparkSinkConfig.DEFAULT_TRANSACTION_TIMEOUT
    +
    +  private val processorMap = new ConcurrentHashMap[CharSequence, TransactionProcessor]()
    +
    +  private var processorFactory: Option[SparkHandlerFactory] = None
    +  private var hostname: String = SparkSinkConfig.DEFAULT_HOSTNAME
    +  private var port: Int = 0
    +  private var maxThreads: Int = SparkSinkConfig.DEFAULT_MAX_THREADS
    +  private var serverOpt: Option[NettyServer] = None
    +  private var running = false
    +
    +  override def start() {
    +    transactionExecutorOpt = Option(Executors.newFixedThreadPool(numProcessors,
    +      new ThreadFactoryBuilder().setDaemon(true)
    +        .setNameFormat("Spark Sink, " + getName + " Processor Thread - %d").build()))
    +
    +    processorFactory = Option(new SparkHandlerFactory(numProcessors))
    +
    +    val responder = new SpecificResponder(classOf[SparkFlumeProtocol], new AvroCallbackHandler())
    +
    +    // Using the constructor that takes specific thread-pools requires bringing in netty
    +    // dependencies which are being excluded in the build. In practice,
    +    // Netty dependencies are already available on the JVM as Flume would have pulled them in.
    +    serverOpt = Option(new NettyServer(responder, new InetSocketAddress(hostname, port)))
    +
    +    serverOpt.map(server => server.start())
    +    lock.lock()
    +    try {
    +      running = true
    +    } finally {
    +      lock.unlock()
    +    }
    +    super.start()
    +  }
    +
    +  override def stop() {
    +    transactionExecutorOpt.map(executor => executor.shutdownNow())
    +    serverOpt.map(server => {
    +      server.close()
    +      server.join()
    +    })
    +    lock.lock()
    +    try {
    +      running = false
    +      blockingCondition.signalAll()
    +    } finally {
    +      lock.unlock()
    +    }
    +  }
    +
    +  override def configure(ctx: Context) {
    +    import SparkSinkConfig._
    +    hostname = ctx.getString(CONF_HOSTNAME, DEFAULT_HOSTNAME)
    +    val portOpt = Option(ctx.getInteger(CONF_PORT))
    +    if(portOpt.isDefined) {
    +      port = portOpt.get
    +    } else {
    +      throw new ConfigurationException("The Port to bind must be specified")
    +    }
    +    numProcessors = ctx.getInteger(PROCESSOR_COUNT, DEFAULT_PROCESSOR_COUNT)
    +    transactionTimeout = ctx.getInteger(CONF_TRANSACTION_TIMEOUT, DEFAULT_TRANSACTION_TIMEOUT)
    +    maxThreads = ctx.getInteger(CONF_MAX_THREADS, DEFAULT_MAX_THREADS)
    +  }
    +
    +  override def process(): Status = {
    +    // This method is called in a loop by the Flume framework - block it until the sink is
    +    // stopped to save CPU resources
    +    lock.lock()
    +    try {
    +      while(running) {
    --- End diff --
    
    Did not know about this! Though I have often used [CountdownLatch.await()](http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/CountDownLatch.html#await()). That does not seem to have the spurious waking up problem. Reduces three variables (lock, running, blockingCondition) to one variable.


---
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 infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] spark pull request: SPARK-1729. Make Flume pull data from source, ...

Posted by tdas <gi...@git.apache.org>.
Github user tdas commented on a diff in the pull request:

    https://github.com/apache/spark/pull/807#discussion_r13473781
  
    --- Diff: external/flume-sink/src/main/scala/org/apache/spark/flume/sink/SparkSink.scala ---
    @@ -0,0 +1,392 @@
    +/*
    + * 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.flume.sink
    +
    +import org.apache.flume.sink.AbstractSink
    +import java.util.concurrent.locks.ReentrantLock
    +import org.apache.flume.Sink.Status
    +import org.apache.spark.flume.{SparkSinkEvent, EventBatch, SparkFlumeProtocol}
    +import scala.util.control.Breaks
    +import java.nio.ByteBuffer
    +import org.apache.flume.{FlumeException, Context}
    +import org.slf4j.LoggerFactory
    +import java.util.concurrent.atomic.AtomicLong
    +import org.apache.commons.lang.RandomStringUtils
    +import java.util.concurrent._
    +import java.util
    +import org.apache.flume.conf.{ConfigurationException, Configurable}
    +import com.google.common.util.concurrent.ThreadFactoryBuilder
    +import org.apache.avro.ipc.NettyServer
    +import org.apache.avro.ipc.specific.SpecificResponder
    +import java.net.InetSocketAddress
    +
    +class SparkSink() extends AbstractSink with Configurable {
    +  private val LOG = LoggerFactory.getLogger(this.getClass)
    +  private val lock = new ReentrantLock()
    +  private val blockingCondition = lock.newCondition()
    +
    +  // This sink will not persist sequence numbers and reuses them if it gets restarted.
    +  // So it is possible to commit a transaction which may have been meant for the sink before the
    +  // restart.
    +  // Since the new txn may not have the same sequence number we must guard against accidentally
    +  // committing
    +  // a new transaction. To reduce the probability of that happening a random string is prepended
    +  // to the sequence number.
    +  // Does not change for life of sink
    +  private val seqBase = RandomStringUtils.randomAlphanumeric(8)
    +  // Incremented for each transaction
    +  private val seqNum = new AtomicLong(0)
    +
    +  private var transactionExecutorOpt: Option[ExecutorService] = None
    +
    +  private var numProcessors: Integer = SparkSinkConfig.DEFAULT_PROCESSOR_COUNT
    +  private var transactionTimeout = SparkSinkConfig.DEFAULT_TRANSACTION_TIMEOUT
    +
    +  private val processorMap = new ConcurrentHashMap[CharSequence, TransactionProcessor]()
    +
    +  private var processorFactory: Option[SparkHandlerFactory] = None
    +  private var hostname: String = SparkSinkConfig.DEFAULT_HOSTNAME
    +  private var port: Int = 0
    +  private var maxThreads: Int = SparkSinkConfig.DEFAULT_MAX_THREADS
    +  private var serverOpt: Option[NettyServer] = None
    +  private var running = false
    +
    +  override def start() {
    +    transactionExecutorOpt = Option(Executors.newFixedThreadPool(numProcessors,
    +      new ThreadFactoryBuilder().setDaemon(true)
    +        .setNameFormat("Spark Sink, " + getName + " Processor Thread - %d").build()))
    +
    +    processorFactory = Option(new SparkHandlerFactory(numProcessors))
    +
    +    val responder = new SpecificResponder(classOf[SparkFlumeProtocol], new AvroCallbackHandler())
    +
    +    // Using the constructor that takes specific thread-pools requires bringing in netty
    +    // dependencies which are being excluded in the build. In practice,
    +    // Netty dependencies are already available on the JVM as Flume would have pulled them in.
    +    serverOpt = Option(new NettyServer(responder, new InetSocketAddress(hostname, port)))
    +
    +    serverOpt.map(server => server.start())
    +    lock.lock()
    +    try {
    +      running = true
    +    } finally {
    +      lock.unlock()
    +    }
    +    super.start()
    +  }
    +
    +  override def stop() {
    +    transactionExecutorOpt.map(executor => executor.shutdownNow())
    +    serverOpt.map(server => {
    +      server.close()
    +      server.join()
    +    })
    +    lock.lock()
    +    try {
    +      running = false
    +      blockingCondition.signalAll()
    +    } finally {
    +      lock.unlock()
    +    }
    +  }
    +
    +  override def configure(ctx: Context) {
    +    import SparkSinkConfig._
    +    hostname = ctx.getString(CONF_HOSTNAME, DEFAULT_HOSTNAME)
    +    val portOpt = Option(ctx.getInteger(CONF_PORT))
    +    if(portOpt.isDefined) {
    +      port = portOpt.get
    +    } else {
    +      throw new ConfigurationException("The Port to bind must be specified")
    +    }
    +    numProcessors = ctx.getInteger(PROCESSOR_COUNT, DEFAULT_PROCESSOR_COUNT)
    +    transactionTimeout = ctx.getInteger(CONF_TRANSACTION_TIMEOUT, DEFAULT_TRANSACTION_TIMEOUT)
    +    maxThreads = ctx.getInteger(CONF_MAX_THREADS, DEFAULT_MAX_THREADS)
    +  }
    +
    +  override def process(): Status = {
    +    // This method is called in a loop by the Flume framework - block it until the sink is
    +    // stopped to save CPU resources
    +    lock.lock()
    +    try {
    +      while(running) {
    --- End diff --
    
    I did some quick tests to test whether CountDownLatch needs to be reseted or not. It doesnt require a reset. As long as the latch count does not reach 0, any call to latch.await() will block (even if other previous calls were interrupted). So it is probably fine to use CountdownLatch


---
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 infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] spark pull request: SPARK-1729. Make Flume pull data from source, ...

Posted by tdas <gi...@git.apache.org>.
Github user tdas commented on the pull request:

    https://github.com/apache/spark/pull/807#issuecomment-49674136
  
    Yeah, and also the hacky script is not seeing the "private[streaming]" in the line before "class FlumePollingInputDStream". I had added that before I knew these corner cases that scripts. Can you fix that as well? 



---
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 infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] spark pull request: [STREAMING] SPARK-1729. Make Flume pull data f...

Posted by tdas <gi...@git.apache.org>.
Github user tdas commented on the pull request:

    https://github.com/apache/spark/pull/807#issuecomment-50380174
  
    Jenkins, test this please.


---
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 infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] spark pull request: SPARK-1729. Make Flume pull data from source, ...

Posted by tdas <gi...@git.apache.org>.
Github user tdas commented on a diff in the pull request:

    https://github.com/apache/spark/pull/807#discussion_r13467510
  
    --- Diff: external/flume-sink/src/main/scala/org/apache/spark/flume/sink/SparkSink.scala ---
    @@ -0,0 +1,392 @@
    +/*
    + * 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.flume.sink
    +
    +import org.apache.flume.sink.AbstractSink
    +import java.util.concurrent.locks.ReentrantLock
    +import org.apache.flume.Sink.Status
    +import org.apache.spark.flume.{SparkSinkEvent, EventBatch, SparkFlumeProtocol}
    +import scala.util.control.Breaks
    +import java.nio.ByteBuffer
    +import org.apache.flume.{FlumeException, Context}
    +import org.slf4j.LoggerFactory
    +import java.util.concurrent.atomic.AtomicLong
    +import org.apache.commons.lang.RandomStringUtils
    +import java.util.concurrent._
    +import java.util
    +import org.apache.flume.conf.{ConfigurationException, Configurable}
    +import com.google.common.util.concurrent.ThreadFactoryBuilder
    +import org.apache.avro.ipc.NettyServer
    +import org.apache.avro.ipc.specific.SpecificResponder
    +import java.net.InetSocketAddress
    +
    +class SparkSink() extends AbstractSink with Configurable {
    +  private val LOG = LoggerFactory.getLogger(this.getClass)
    +  private val lock = new ReentrantLock()
    +  private val blockingCondition = lock.newCondition()
    +
    +  // This sink will not persist sequence numbers and reuses them if it gets restarted.
    +  // So it is possible to commit a transaction which may have been meant for the sink before the
    +  // restart.
    +  // Since the new txn may not have the same sequence number we must guard against accidentally
    +  // committing
    +  // a new transaction. To reduce the probability of that happening a random string is prepended
    +  // to the sequence number.
    +  // Does not change for life of sink
    +  private val seqBase = RandomStringUtils.randomAlphanumeric(8)
    +  // Incremented for each transaction
    +  private val seqNum = new AtomicLong(0)
    +
    +  private var transactionExecutorOpt: Option[ExecutorService] = None
    +
    +  private var numProcessors: Integer = SparkSinkConfig.DEFAULT_PROCESSOR_COUNT
    +  private var transactionTimeout = SparkSinkConfig.DEFAULT_TRANSACTION_TIMEOUT
    +
    +  private val processorMap = new ConcurrentHashMap[CharSequence, TransactionProcessor]()
    +
    +  private var processorFactory: Option[SparkHandlerFactory] = None
    +  private var hostname: String = SparkSinkConfig.DEFAULT_HOSTNAME
    +  private var port: Int = 0
    +  private var maxThreads: Int = SparkSinkConfig.DEFAULT_MAX_THREADS
    +  private var serverOpt: Option[NettyServer] = None
    +  private var running = false
    +
    +  override def start() {
    +    transactionExecutorOpt = Option(Executors.newFixedThreadPool(numProcessors,
    +      new ThreadFactoryBuilder().setDaemon(true)
    +        .setNameFormat("Spark Sink, " + getName + " Processor Thread - %d").build()))
    +
    +    processorFactory = Option(new SparkHandlerFactory(numProcessors))
    +
    +    val responder = new SpecificResponder(classOf[SparkFlumeProtocol], new AvroCallbackHandler())
    +
    +    // Using the constructor that takes specific thread-pools requires bringing in netty
    +    // dependencies which are being excluded in the build. In practice,
    +    // Netty dependencies are already available on the JVM as Flume would have pulled them in.
    +    serverOpt = Option(new NettyServer(responder, new InetSocketAddress(hostname, port)))
    +
    +    serverOpt.map(server => server.start())
    +    lock.lock()
    +    try {
    +      running = true
    +    } finally {
    +      lock.unlock()
    +    }
    +    super.start()
    +  }
    +
    +  override def stop() {
    +    transactionExecutorOpt.map(executor => executor.shutdownNow())
    +    serverOpt.map(server => {
    +      server.close()
    +      server.join()
    +    })
    +    lock.lock()
    +    try {
    +      running = false
    +      blockingCondition.signalAll()
    +    } finally {
    +      lock.unlock()
    +    }
    +  }
    +
    +  override def configure(ctx: Context) {
    +    import SparkSinkConfig._
    +    hostname = ctx.getString(CONF_HOSTNAME, DEFAULT_HOSTNAME)
    +    val portOpt = Option(ctx.getInteger(CONF_PORT))
    +    if(portOpt.isDefined) {
    +      port = portOpt.get
    +    } else {
    +      throw new ConfigurationException("The Port to bind must be specified")
    +    }
    +    numProcessors = ctx.getInteger(PROCESSOR_COUNT, DEFAULT_PROCESSOR_COUNT)
    +    transactionTimeout = ctx.getInteger(CONF_TRANSACTION_TIMEOUT, DEFAULT_TRANSACTION_TIMEOUT)
    +    maxThreads = ctx.getInteger(CONF_MAX_THREADS, DEFAULT_MAX_THREADS)
    +  }
    +
    +  override def process(): Status = {
    +    // This method is called in a loop by the Flume framework - block it until the sink is
    +    // stopped to save CPU resources
    +    lock.lock()
    +    try {
    +      while(running) {
    +        blockingCondition.await()
    +      }
    +    } finally {
    +      lock.unlock()
    +    }
    +    Status.BACKOFF
    +  }
    +
    +
    +  // Object representing an empty batch returned by the txn processor due to some error.
    +  case object ErrorEventBatch extends EventBatch
    +
    +  private class AvroCallbackHandler() extends SparkFlumeProtocol {
    +
    +    override def getEventBatch(n: Int): EventBatch = {
    +      val processor = processorFactory.get.checkOut(n)
    +      transactionExecutorOpt.map(executor => executor.submit(processor))
    +      // Wait until a batch is available - can be null if some error was thrown
    +      val eventBatch = processor.eventQueue.take()
    +      eventBatch match {
    +        case ErrorEventBatch => throw new FlumeException("Something went wrong. No events" +
    +          " retrieved from channel.")
    +        case events => {
    +          processorMap.put(events.getSequenceNumber, processor)
    +          if (LOG.isDebugEnabled) {
    +            LOG.debug("Sent " + events.getEventBatch.size() +
    +              " events with sequence number: " + events.getSequenceNumber)
    +          }
    +          events
    +        }
    +      }
    +    }
    +
    +    override def ack(sequenceNumber: CharSequence): Void = {
    +      completeTransaction(sequenceNumber, success = true)
    +      null
    +    }
    +
    +    override def nack(sequenceNumber: CharSequence): Void = {
    +      completeTransaction(sequenceNumber, success = false)
    +      LOG.info("Spark failed to commit transaction. Will reattempt events.")
    +      null
    +    }
    +
    +    def completeTransaction(sequenceNumber: CharSequence, success: Boolean) {
    +      val processorOpt = Option(processorMap.remove(sequenceNumber))
    +      if (processorOpt.isDefined) {
    +        val processor = processorOpt.get
    +        processor.resultQueueUpdateLock.lock()
    +        try {
    +          // Is the sequence number the same as the one the processor is processing? If not,
    +          // don't update {
    +          if (processor.eventBatch.getSequenceNumber.equals(sequenceNumber)) {
    +            processor.resultQueue.put(success)
    +          }
    +        } finally {
    +          processor.resultQueueUpdateLock.unlock()
    +        }
    +      }
    +    }
    +  }
    +
    +  // Flume forces transactions to be thread-local (horrible, I know!)
    +  // So the sink basically spawns a new thread to pull the events out within a transaction.
    +  // The thread fills in the event batch object that is set before the thread is scheduled.
    +  // After filling it in, the thread waits on a condition - which is released only
    +  // when the success message comes back for the specific sequence number for that event batch.
    +  /**
    +   * This class represents a transaction on the Flume channel. This class runs a separate thread
    +   * which owns the transaction. It is blocked until the success call for that transaction comes
    +   * back.
    +   * @param maxBatchSize
    +   */
    +  private class TransactionProcessor(var maxBatchSize: Int) extends Callable[Void] {
    +    // Must be set to a new event batch before scheduling this!!
    +    val eventBatch = new EventBatch("", new util.LinkedList[SparkSinkEvent])
    +    val eventQueue = new SynchronousQueue[EventBatch]()
    +    val resultQueue = new SynchronousQueue[Boolean]()
    +    val resultQueueUpdateLock = new ReentrantLock()
    +
    +    object Zero {
    +      val zero = "0" // Oh, I miss static finals
    +    }
    +
    +
    +    override def call(): Void = {
    +      val tx = getChannel.getTransaction
    +      tx.begin()
    +      try {
    +        eventBatch.setSequenceNumber(seqBase + seqNum.incrementAndGet())
    +        val events = eventBatch.getEventBatch
    +        events.clear()
    +        val loop = new Breaks
    +        var gotEventsInThisTxn = false
    +        loop.breakable {
    +          var i = 0
    +          // Using for here causes the maxBatchSize change to be ineffective as the Range gets
    +          // pregenerated
    +          while (i < maxBatchSize) {
    +            i += 1
    +            val eventOpt = Option(getChannel.take())
    +            eventOpt.map(event => {
    +              events.add(new SparkSinkEvent(toCharSequenceMap(event
    +                .getHeaders),
    +                ByteBuffer.wrap(event.getBody)))
    +              gotEventsInThisTxn = true
    +            })
    +            if (eventOpt.isEmpty) {
    +              if (!gotEventsInThisTxn) {
    +                // To avoid sending empty batches, we wait till events are available backing off
    +                // between attempts to get events. Each attempt to get an event though causes one
    +                // iteration to be lost. To ensure that we still send back maxBatchSize number of
    +                // events, we cheat and increase the maxBatchSize by 1 to account for the lost
    +                // iteration. Even throwing an exception is expensive as Avro will serialize it
    +                // and send it over the wire, which is useless. Before incrementing though,
    +                // ensure that we are not anywhere near INT_MAX.
    +                if (maxBatchSize >= Int.MaxValue / 2) {
    +                  // Random sanity check
    +                  throw new RuntimeException("Safety exception - polled too many times, no events!")
    +                }
    +                maxBatchSize += 1
    +                Thread.sleep(500)
    +              } else {
    +                loop.break()
    +              }
    +            }
    +          }
    +        }
    +        // Make the data available to the sender thread
    +        eventQueue.put(eventBatch)
    +
    +        // Wait till timeout for the ack/nack
    +        val maybeResult = Option(resultQueue.poll(transactionTimeout, TimeUnit.SECONDS))
    +        // There is a race condition here.
    +        // 1. This times out.
    +        // 2. The result is empty, so timeout exception is thrown.
    +        // 3. The ack comes in before the finally block is entered
    +        // 4. The thread with the ack has a handle to this processor,
    +        // and another thread has the same processor checked out
    +        // (since the finally block was executed and the processor checked back in)
    +        // 5. The thread with the ack now updates the result queue,
    +        // so the processor thinks it is the ack for the current batch.
    +        // To avoid this - update the sequence number to "0" (with or without a result - does not
    +        // matter).
    +        // In the ack method, check if the seq number is the same as the processor's -
    +        // if they are then update the result queue. Now if the
    +        // processor updates the seq number first - the ack/nack never updates the result. If the
    +        // ack/nack updates the
    +        // result after the timeout but before the seq number is updated to "0" it does not
    +        // matter - the processor would
    +        // still timeout and the result is cleared before reusing the processor.
    +        // Unfortunately, this needs to be done from within a lock
    +        // to make sure that the new sequence number is actually visible to the ack thread
    +        // (happens-before)
    +        resultQueueUpdateLock.lock()
    +        try {
    +          eventBatch.setSequenceNumber(Zero.zero)
    +        } finally {
    +          resultQueueUpdateLock.unlock()
    +        }
    +        eventBatch.getEventBatch.clear()
    +        // If the batch failed on spark side, throw a FlumeException
    +        maybeResult.map(success =>
    +          if (!success) {
    +            throw new
    +                FlumeException("Spark could not accept events. The transaction will be retried.")
    +          }
    +        )
    +        // If the operation timed out, throw a TimeoutException
    +        if (maybeResult.isEmpty) {
    +          throw new TimeoutException("Spark did not respond within the timeout period of " +
    +            transactionTimeout + "seconds. Transaction will be retried")
    +        }
    +        null
    +      } catch {
    +        case e: Throwable =>
    +          try {
    +            LOG.warn("Error while attempting to remove events from the channel.", e)
    +            tx.rollback()
    +          } catch {
    +            case e1: Throwable => LOG.error(
    +              "Rollback failed while attempting to rollback due to commit failure.", e1)
    +          }
    +          null // No point rethrowing the exception
    +      } finally {
    +        // Must *always* release the caller thread
    +        eventQueue.put(ErrorEventBatch)
    +        // In the case of success coming after the timeout, but before resetting the seq number
    +        // remove the event from the map and then clear the value
    +        resultQueue.clear()
    +        processorMap.remove(eventBatch.getSequenceNumber)
    +        processorFactory.get.checkIn(this)
    +        tx.close()
    +      }
    +    }
    +
    +    def toCharSequenceMap(inMap: java.util.Map[String, String]): java.util.Map[CharSequence,
    +      CharSequence] = {
    +      val charSeqMap = new util.HashMap[CharSequence, CharSequence](inMap.size())
    +      charSeqMap.putAll(inMap)
    +      charSeqMap
    +    }
    +  }
    +
    +  private class SparkHandlerFactory(val maxInstances: Int) {
    +    val queue = new scala.collection.mutable.Queue[TransactionProcessor]
    +    val queueModificationLock = new ReentrantLock()
    +    var currentSize = 0
    +    val waitForCheckIn = queueModificationLock.newCondition()
    +
    +    def checkOut(n: Int): TransactionProcessor = {
    +      def getProcessor = {
    +        val processor = queue.dequeue()
    +        processor.maxBatchSize = n
    +        processor
    +      }
    +      queueModificationLock.lock()
    +      try {
    +        if (queue.size > 0) {
    +          getProcessor
    +        }
    +        else {
    +          if (currentSize < maxInstances) {
    +            currentSize += 1
    +            new TransactionProcessor(n)
    +          } else {
    +            // No events in queue and cannot initialize more!
    +            // Since currentSize never reduces, queue size increasing is the only hope
    +            while (queue.size == 0 && currentSize >= maxInstances) {
    +              waitForCheckIn.await()
    +            }
    +            getProcessor
    +          }
    +        }
    +      } finally {
    +        queueModificationLock.unlock()
    +      }
    +    }
    +
    +    def checkIn(processor: TransactionProcessor) {
    +      queueModificationLock.lock()
    --- End diff --
    
    Well you can do that with ArrayBlockingQueue of fixed size. The code will be more concise as you wont need `waitForChecking` (as `blockingQueue.take()` will block until an item is available in the queue) and you wont need `queueModificationLock` (as all operations on blockingQueue are synchronized).


---
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 infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] spark pull request: [STREAMING] SPARK-1729. Make Flume pull data f...

Posted by SparkQA <gi...@git.apache.org>.
Github user SparkQA commented on the pull request:

    https://github.com/apache/spark/pull/807#issuecomment-50387912
  
    QA results for PR 807:<br>- This patch FAILED unit tests.<br>- This patch merges cleanly<br>- This patch adds the following public classes (experimental):<br>class SparkSink extends AbstractSink with Logging with Configurable {<br><br>For more information see test ouptut:<br>https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/17298/consoleFull


---
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 infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] spark pull request: SPARK-1729. Make Flume pull data from source, ...

Posted by tdas <gi...@git.apache.org>.
Github user tdas commented on a diff in the pull request:

    https://github.com/apache/spark/pull/807#discussion_r13838400
  
    --- Diff: external/flume-sink/src/main/scala/org/apache/spark/flume/sink/SparkSink.scala ---
    @@ -0,0 +1,432 @@
    +/*
    + * 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.flume.sink
    +
    +import java.net.InetSocketAddress
    +import java.nio.ByteBuffer
    +import java.util
    +import java.util.concurrent._
    +import java.util.concurrent.atomic.AtomicLong
    +
    +import scala.util.control.Breaks
    +
    +import com.google.common.util.concurrent.ThreadFactoryBuilder
    +import org.apache.avro.ipc.NettyServer
    +import org.apache.avro.ipc.specific.SpecificResponder
    +import org.apache.commons.lang.RandomStringUtils
    +import org.apache.flume.Sink.Status
    +import org.apache.flume.conf.{ConfigurationException, Configurable}
    +import org.apache.flume.sink.AbstractSink
    +import org.apache.flume.{Channel, Transaction, FlumeException, Context}
    +import org.slf4j.LoggerFactory
    +
    +import org.apache.spark.flume.{SparkSinkEvent, EventBatch, SparkFlumeProtocol}
    +
    +/**
    + * A sink that uses Avro RPC to run a server that can be polled by Spark's
    + * FlumePollingInputDStream. This sink has the following configuration parameters:
    + *
    + * hostname - The hostname to bind to. Default: 0.0.0.0
    + * port - The port to bind to. (No default - mandatory)
    + * timeout - Time in seconds after which a transaction is rolled back,
    + * if an ACK is not received from Spark within that time
    + * threads - Number of threads to use to receive requests from Spark (Default: 10)
    + *
    + */
    +// Flume forces transactions to be thread-local. So each transaction *must* be committed, or
    +// rolled back from the thread it was originally created in. So each getEvents call from Spark
    +// creates a TransactionProcessor which runs in a new thread, in which the transaction is created
    +// and events are pulled off the channel. Once the events are sent to spark,
    +// that thread is blocked and the TransactionProcessor is saved in a map,
    +// until an ACK or NACK comes back or the transaction times out (after the specified timeout).
    +// When the response comes, the TransactionProcessor is retrieved and then unblocked,
    +// at which point the transaction is committed or rolled back.
    +class SparkSink extends AbstractSink with Configurable {
    +
    +  // Size of the pool to use for holding transaction processors.
    +  private var poolSize: Integer = SparkSinkConfig.DEFAULT_THREADS
    +
    +  // Timeout for each transaction. If spark does not respond in this much time,
    +  // rollback the transaction
    +  private var transactionTimeout = SparkSinkConfig.DEFAULT_TRANSACTION_TIMEOUT
    +
    +  // Address info to bind on
    +  private var hostname: String = SparkSinkConfig.DEFAULT_HOSTNAME
    +  private var port: Int = 0
    +
    +  // Handle to the server
    +  private var serverOpt: Option[NettyServer] = None
    +
    +  // The handler that handles the callback from Avro
    +  private var handler: Option[SparkAvroCallbackHandler] = None
    +
    +  // Latch that blocks off the Flume framework from wasting 1 thread.
    +  private val blockingLatch = new CountDownLatch(1)
    +
    +  override def start() {
    +    handler = Option(new SparkAvroCallbackHandler(poolSize, getChannel, transactionTimeout))
    +    val responder = new SpecificResponder(classOf[SparkFlumeProtocol], handler.get)
    +    // Using the constructor that takes specific thread-pools requires bringing in netty
    +    // dependencies which are being excluded in the build. In practice,
    +    // Netty dependencies are already available on the JVM as Flume would have pulled them in.
    +    serverOpt = Option(new NettyServer(responder, new InetSocketAddress(hostname, port)))
    +    serverOpt.map(server => {
    +      server.start()
    +    })
    +    super.start()
    +  }
    +
    +  override def stop() {
    +    handler.map(callbackHandler => {
    +      callbackHandler.shutdown()
    +    })
    +    serverOpt.map(server => {
    +      server.close()
    +      server.join()
    +    })
    +    blockingLatch.countDown()
    +    super.stop()
    +  }
    +
    +  /**
    +   * @param ctx
    +   */
    +  override def configure(ctx: Context) {
    +    import SparkSinkConfig._
    +    hostname = ctx.getString(CONF_HOSTNAME, DEFAULT_HOSTNAME)
    +    port = Option(ctx.getInteger(CONF_PORT)).
    +      getOrElse(throw new ConfigurationException("The port to bind to must be specified"))
    +    poolSize = ctx.getInteger(THREADS, DEFAULT_THREADS)
    +    transactionTimeout = ctx.getInteger(CONF_TRANSACTION_TIMEOUT, DEFAULT_TRANSACTION_TIMEOUT)
    +  }
    +
    +  override def process(): Status = {
    +    // This method is called in a loop by the Flume framework - block it until the sink is
    +    // stopped to save CPU resources. The sink runner will interrupt this thread when the sink is
    +    // being shut down.
    +    blockingLatch.await()
    +    Status.BACKOFF
    +  }
    +}
    +
    +/**
    + * Class that implements the SparkFlumeProtocol, that is used by the Avro Netty Server to process
    + * requests. Each getEvents, ack and nack call is forwarded to an instance of this class.
    + * @param threads Number of threads to use to process requests.
    + * @param channel The channel that the sink pulls events from
    + * @param transactionTimeout Timeout in millis after which the transaction if not acked by Spark
    + *                           is rolled back.
    + */
    +private class SparkAvroCallbackHandler(val threads: Int, val channel: Channel,
    +  val transactionTimeout: Int) extends SparkFlumeProtocol {
    +  private val LOG = LoggerFactory.getLogger(classOf[SparkAvroCallbackHandler])
    +  val transactionExecutorOpt = Option(Executors.newFixedThreadPool(threads,
    +    new ThreadFactoryBuilder().setDaemon(true)
    +      .setNameFormat("Spark Sink Processor Thread - %d").build()))
    +  private val processorMap = new ConcurrentHashMap[CharSequence, TransactionProcessor]()
    +  // This sink will not persist sequence numbers and reuses them if it gets restarted.
    +  // So it is possible to commit a transaction which may have been meant for the sink before the
    +  // restart.
    +  // Since the new txn may not have the same sequence number we must guard against accidentally
    +  // committing a new transaction. To reduce the probability of that happening a random string is
    +  // prepended to the sequence number. Does not change for life of sink
    +  private val seqBase = RandomStringUtils.randomAlphanumeric(8)
    +  private val seqCounter = new AtomicLong(0)
    +
    +  /**
    +   * Returns a bunch of events to Spark over Avro RPC.
    +   * @param n Maximum number of events to return in a batch
    +   * @return [[EventBatch]] instance that has a sequence number and an array of at most n events
    +   */
    +  override def getEventBatch(n: Int): EventBatch = {
    +    val sequenceNumber = seqBase + seqCounter.incrementAndGet()
    +    val processor = new TransactionProcessor(channel, sequenceNumber,
    +      n, transactionTimeout, this)
    +    transactionExecutorOpt.map(executor => {
    +      executor.submit(processor)
    +    })
    +    // Wait until a batch is available - can be null if some error was thrown
    +    processor.getEventBatch match {
    +      case ErrorEventBatch => throw new FlumeException("Something went wrong. No events" +
    +        " retrieved from channel.")
    +      case eventBatch: EventBatch =>
    +        processorMap.put(sequenceNumber, processor)
    +        if (LOG.isDebugEnabled()) {
    +          LOG.debug("Sent " + eventBatch.getEvents.size() +
    +            " events with sequence number: " + eventBatch.getSequenceNumber)
    +        }
    +        eventBatch
    +    }
    +  }
    +
    +  /**
    +   * Called by Spark to indicate successful commit of a batch
    +   * @param sequenceNumber The sequence number of the event batch that was successful
    +   */
    +  override def ack(sequenceNumber: CharSequence): Void = {
    +    completeTransaction(sequenceNumber, success = true)
    +    null
    +  }
    +
    +  /**
    +   * Called by Spark to indicate failed commit of a batch
    +   * @param sequenceNumber The sequence number of the event batch that failed
    +   * @return
    +   */
    +  override def nack(sequenceNumber: CharSequence): Void = {
    +    completeTransaction(sequenceNumber, success = false)
    +    LOG.info("Spark failed to commit transaction. Will reattempt events.")
    +    null
    +  }
    +
    +  /**
    +   * Helper method to commit or rollback a transaction.
    +   * @param sequenceNumber The sequence number of the batch that was completed
    +   * @param success Whether the batch was successful or not.
    +   */
    +  private def completeTransaction(sequenceNumber: CharSequence, success: Boolean) {
    +    Option(removeAndGetProcessor(sequenceNumber)).map(processor => {
    +      processor.batchProcessed(success)
    +    })
    +  }
    +
    +  /**
    +   * Helper method to remove the TxnProcessor for a Sequence Number. Can be used to avoid a leak.
    +   * @param sequenceNumber
    +   * @return The transaction processor for the corresponding batch. Note that this instance is no
    +   *         longer tracked and the caller is responsible for that txn processor.
    +   */
    +  private[flume] def removeAndGetProcessor(sequenceNumber: CharSequence): TransactionProcessor = {
    +    processorMap.remove(sequenceNumber.toString) // The toString is required!
    +  }
    +
    +  /**
    +   * Shuts down the executor used to process transactions.
    +   */
    +  def shutdown() {
    +    transactionExecutorOpt.map(executor => {
    +      executor.shutdownNow()
    +    })
    +  }
    +}
    +
    +/**
    + * Object representing an empty batch returned by the txn processor due to some error.
    + */
    +case object ErrorEventBatch extends EventBatch
    --- End diff --
    
    But the spark streaming side would not know anything about why it failed. Was it a failure to create transaction, or some exception in get data from upstream. 
    
    So does it make sense to have something like `class ErrorEventBatch(reason: String) extend EventBatch` which is created and returned in case of an exception (the reason having the exception string)? Then on the spark streaming we will have more information to debug, isnt it?



---
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 infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] spark pull request: SPARK-1729. Make Flume pull data from source, ...

Posted by tdas <gi...@git.apache.org>.
Github user tdas commented on a diff in the pull request:

    https://github.com/apache/spark/pull/807#discussion_r15200789
  
    --- Diff: external/flume/src/main/scala/org/apache/spark/streaming/flume/EventTransformer.scala ---
    @@ -0,0 +1,72 @@
    +/*
    + * 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.streaming.flume
    +
    +import java.io.{ObjectOutput, ObjectInput}
    +
    +import scala.collection.JavaConversions._
    +
    +import org.apache.spark.util.Utils
    +import org.apache.spark.Logging
    +
    +/**
    + * A simple object that provides the implementation of readExternal and writeExternal for both
    + * the wrapper classes for Flume-style Events.
    + */
    +object EventTransformer extends Logging {
    --- End diff --
    
    Please add private[flume] to this.


---
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 infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] spark pull request: SPARK-1729. Make Flume pull data from source, ...

Posted by tdas <gi...@git.apache.org>.
Github user tdas commented on the pull request:

    https://github.com/apache/spark/pull/807#issuecomment-49673163
  
    Jenkins, test this please.


---
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 infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] spark pull request: SPARK-1729. Make Flume pull data from source, ...

Posted by harishreedharan <gi...@git.apache.org>.
Github user harishreedharan commented on a diff in the pull request:

    https://github.com/apache/spark/pull/807#discussion_r13471158
  
    --- Diff: external/flume-sink/src/main/scala/org/apache/spark/flume/sink/SparkSink.scala ---
    @@ -0,0 +1,392 @@
    +/*
    + * 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.flume.sink
    +
    +import org.apache.flume.sink.AbstractSink
    +import java.util.concurrent.locks.ReentrantLock
    +import org.apache.flume.Sink.Status
    +import org.apache.spark.flume.{SparkSinkEvent, EventBatch, SparkFlumeProtocol}
    +import scala.util.control.Breaks
    +import java.nio.ByteBuffer
    +import org.apache.flume.{FlumeException, Context}
    +import org.slf4j.LoggerFactory
    +import java.util.concurrent.atomic.AtomicLong
    +import org.apache.commons.lang.RandomStringUtils
    +import java.util.concurrent._
    +import java.util
    +import org.apache.flume.conf.{ConfigurationException, Configurable}
    +import com.google.common.util.concurrent.ThreadFactoryBuilder
    +import org.apache.avro.ipc.NettyServer
    +import org.apache.avro.ipc.specific.SpecificResponder
    +import java.net.InetSocketAddress
    +
    +class SparkSink() extends AbstractSink with Configurable {
    +  private val LOG = LoggerFactory.getLogger(this.getClass)
    +  private val lock = new ReentrantLock()
    +  private val blockingCondition = lock.newCondition()
    +
    +  // This sink will not persist sequence numbers and reuses them if it gets restarted.
    +  // So it is possible to commit a transaction which may have been meant for the sink before the
    +  // restart.
    +  // Since the new txn may not have the same sequence number we must guard against accidentally
    +  // committing
    +  // a new transaction. To reduce the probability of that happening a random string is prepended
    +  // to the sequence number.
    +  // Does not change for life of sink
    +  private val seqBase = RandomStringUtils.randomAlphanumeric(8)
    +  // Incremented for each transaction
    +  private val seqNum = new AtomicLong(0)
    +
    +  private var transactionExecutorOpt: Option[ExecutorService] = None
    +
    +  private var numProcessors: Integer = SparkSinkConfig.DEFAULT_PROCESSOR_COUNT
    +  private var transactionTimeout = SparkSinkConfig.DEFAULT_TRANSACTION_TIMEOUT
    +
    +  private val processorMap = new ConcurrentHashMap[CharSequence, TransactionProcessor]()
    +
    +  private var processorFactory: Option[SparkHandlerFactory] = None
    +  private var hostname: String = SparkSinkConfig.DEFAULT_HOSTNAME
    +  private var port: Int = 0
    +  private var maxThreads: Int = SparkSinkConfig.DEFAULT_MAX_THREADS
    +  private var serverOpt: Option[NettyServer] = None
    +  private var running = false
    +
    +  override def start() {
    +    transactionExecutorOpt = Option(Executors.newFixedThreadPool(numProcessors,
    +      new ThreadFactoryBuilder().setDaemon(true)
    +        .setNameFormat("Spark Sink, " + getName + " Processor Thread - %d").build()))
    +
    +    processorFactory = Option(new SparkHandlerFactory(numProcessors))
    +
    +    val responder = new SpecificResponder(classOf[SparkFlumeProtocol], new AvroCallbackHandler())
    +
    +    // Using the constructor that takes specific thread-pools requires bringing in netty
    +    // dependencies which are being excluded in the build. In practice,
    +    // Netty dependencies are already available on the JVM as Flume would have pulled them in.
    +    serverOpt = Option(new NettyServer(responder, new InetSocketAddress(hostname, port)))
    +
    +    serverOpt.map(server => server.start())
    +    lock.lock()
    +    try {
    +      running = true
    +    } finally {
    +      lock.unlock()
    +    }
    +    super.start()
    +  }
    +
    +  override def stop() {
    --- End diff --
    
    Yep, my mistake.


---
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 infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] spark pull request: [STREAMING] SPARK-1729. Make Flume pull data f...

Posted by harishreedharan <gi...@git.apache.org>.
Github user harishreedharan commented on the pull request:

    https://github.com/apache/spark/pull/807#issuecomment-50391695
  
    Thanks @tdas! I was trying to figure it out when I saw the failure - but I can't see a place to add the exclusions.


---
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 infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] spark pull request: SPARK-1729. Make Flume pull data from source, ...

Posted by pwendell <gi...@git.apache.org>.
Github user pwendell commented on the pull request:

    https://github.com/apache/spark/pull/807#issuecomment-49703872
  
    Hey folks - I just took a light pass on this.
    
    One thing I'm a bit confused about - the sink here is not really specific to Spark at all (there is no dependency on Spark). The classes used are entirely general avro classes that other applications could use easily. So why is this being contributed to Spark instead of being put inside of Flume as a general purpose sink that supports polling from external sources? I could imagine that other systems might also want to integrate with flume via a pull/polling based model than via a push model.
    
    Was there any previous consideration to put this directly in the Flume project?
    
    Adding this in Spark adds some nontrivial steps to the Spark build (such as an avro compiler). So naturally a question is whether it belongs in Spark or Flume. I don't think we can easily change this later since we expose the `SparkFlumePollingEvent` type directly to users, and that type is in the spark package. Actually one related thing, can we not convert these to `SparkFlumeEvents`'s so that the types do not differ depending on which type of flume integration they are using? This could be confusing for users to have to deal with a different type.
    



---
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 infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] spark pull request: SPARK-1729. Make Flume pull data from source, ...

Posted by rxin <gi...@git.apache.org>.
Github user rxin commented on the pull request:

    https://github.com/apache/spark/pull/807#issuecomment-43465460
  
    @pwendell @tdas


---
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 infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] spark pull request: SPARK-1729. Make Flume pull data from source, ...

Posted by tdas <gi...@git.apache.org>.
Github user tdas commented on a diff in the pull request:

    https://github.com/apache/spark/pull/807#discussion_r13463949
  
    --- Diff: external/flume-sink/src/main/scala/org/apache/spark/flume/sink/SparkSink.scala ---
    @@ -0,0 +1,392 @@
    +/*
    + * 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.flume.sink
    +
    +import org.apache.flume.sink.AbstractSink
    +import java.util.concurrent.locks.ReentrantLock
    +import org.apache.flume.Sink.Status
    +import org.apache.spark.flume.{SparkSinkEvent, EventBatch, SparkFlumeProtocol}
    +import scala.util.control.Breaks
    +import java.nio.ByteBuffer
    +import org.apache.flume.{FlumeException, Context}
    +import org.slf4j.LoggerFactory
    +import java.util.concurrent.atomic.AtomicLong
    +import org.apache.commons.lang.RandomStringUtils
    +import java.util.concurrent._
    +import java.util
    +import org.apache.flume.conf.{ConfigurationException, Configurable}
    +import com.google.common.util.concurrent.ThreadFactoryBuilder
    +import org.apache.avro.ipc.NettyServer
    +import org.apache.avro.ipc.specific.SpecificResponder
    +import java.net.InetSocketAddress
    +
    +class SparkSink() extends AbstractSink with Configurable {
    +  private val LOG = LoggerFactory.getLogger(this.getClass)
    +  private val lock = new ReentrantLock()
    +  private val blockingCondition = lock.newCondition()
    +
    +  // This sink will not persist sequence numbers and reuses them if it gets restarted.
    +  // So it is possible to commit a transaction which may have been meant for the sink before the
    +  // restart.
    +  // Since the new txn may not have the same sequence number we must guard against accidentally
    +  // committing
    +  // a new transaction. To reduce the probability of that happening a random string is prepended
    +  // to the sequence number.
    +  // Does not change for life of sink
    +  private val seqBase = RandomStringUtils.randomAlphanumeric(8)
    +  // Incremented for each transaction
    +  private val seqNum = new AtomicLong(0)
    +
    +  private var transactionExecutorOpt: Option[ExecutorService] = None
    +
    +  private var numProcessors: Integer = SparkSinkConfig.DEFAULT_PROCESSOR_COUNT
    +  private var transactionTimeout = SparkSinkConfig.DEFAULT_TRANSACTION_TIMEOUT
    +
    +  private val processorMap = new ConcurrentHashMap[CharSequence, TransactionProcessor]()
    +
    +  private var processorFactory: Option[SparkHandlerFactory] = None
    +  private var hostname: String = SparkSinkConfig.DEFAULT_HOSTNAME
    +  private var port: Int = 0
    +  private var maxThreads: Int = SparkSinkConfig.DEFAULT_MAX_THREADS
    +  private var serverOpt: Option[NettyServer] = None
    +  private var running = false
    +
    +  override def start() {
    +    transactionExecutorOpt = Option(Executors.newFixedThreadPool(numProcessors,
    +      new ThreadFactoryBuilder().setDaemon(true)
    +        .setNameFormat("Spark Sink, " + getName + " Processor Thread - %d").build()))
    +
    +    processorFactory = Option(new SparkHandlerFactory(numProcessors))
    +
    +    val responder = new SpecificResponder(classOf[SparkFlumeProtocol], new AvroCallbackHandler())
    +
    +    // Using the constructor that takes specific thread-pools requires bringing in netty
    +    // dependencies which are being excluded in the build. In practice,
    +    // Netty dependencies are already available on the JVM as Flume would have pulled them in.
    +    serverOpt = Option(new NettyServer(responder, new InetSocketAddress(hostname, port)))
    +
    +    serverOpt.map(server => server.start())
    +    lock.lock()
    +    try {
    +      running = true
    +    } finally {
    +      lock.unlock()
    +    }
    +    super.start()
    +  }
    +
    +  override def stop() {
    +    transactionExecutorOpt.map(executor => executor.shutdownNow())
    +    serverOpt.map(server => {
    +      server.close()
    +      server.join()
    +    })
    +    lock.lock()
    +    try {
    +      running = false
    +      blockingCondition.signalAll()
    +    } finally {
    +      lock.unlock()
    +    }
    +  }
    +
    +  override def configure(ctx: Context) {
    +    import SparkSinkConfig._
    +    hostname = ctx.getString(CONF_HOSTNAME, DEFAULT_HOSTNAME)
    +    val portOpt = Option(ctx.getInteger(CONF_PORT))
    +    if(portOpt.isDefined) {
    +      port = portOpt.get
    +    } else {
    +      throw new ConfigurationException("The Port to bind must be specified")
    +    }
    +    numProcessors = ctx.getInteger(PROCESSOR_COUNT, DEFAULT_PROCESSOR_COUNT)
    +    transactionTimeout = ctx.getInteger(CONF_TRANSACTION_TIMEOUT, DEFAULT_TRANSACTION_TIMEOUT)
    +    maxThreads = ctx.getInteger(CONF_MAX_THREADS, DEFAULT_MAX_THREADS)
    +  }
    +
    +  override def process(): Status = {
    +    // This method is called in a loop by the Flume framework - block it until the sink is
    +    // stopped to save CPU resources
    +    lock.lock()
    +    try {
    +      while(running) {
    +        blockingCondition.await()
    +      }
    +    } finally {
    +      lock.unlock()
    +    }
    +    Status.BACKOFF
    +  }
    +
    +
    +  // Object representing an empty batch returned by the txn processor due to some error.
    +  case object ErrorEventBatch extends EventBatch
    +
    +  private class AvroCallbackHandler() extends SparkFlumeProtocol {
    +
    +    override def getEventBatch(n: Int): EventBatch = {
    +      val processor = processorFactory.get.checkOut(n)
    +      transactionExecutorOpt.map(executor => executor.submit(processor))
    +      // Wait until a batch is available - can be null if some error was thrown
    +      val eventBatch = processor.eventQueue.take()
    +      eventBatch match {
    +        case ErrorEventBatch => throw new FlumeException("Something went wrong. No events" +
    +          " retrieved from channel.")
    +        case events => {
    +          processorMap.put(events.getSequenceNumber, processor)
    +          if (LOG.isDebugEnabled) {
    +            LOG.debug("Sent " + events.getEventBatch.size() +
    +              " events with sequence number: " + events.getSequenceNumber)
    +          }
    +          events
    +        }
    +      }
    +    }
    +
    +    override def ack(sequenceNumber: CharSequence): Void = {
    +      completeTransaction(sequenceNumber, success = true)
    +      null
    +    }
    +
    +    override def nack(sequenceNumber: CharSequence): Void = {
    +      completeTransaction(sequenceNumber, success = false)
    +      LOG.info("Spark failed to commit transaction. Will reattempt events.")
    +      null
    +    }
    +
    +    def completeTransaction(sequenceNumber: CharSequence, success: Boolean) {
    +      val processorOpt = Option(processorMap.remove(sequenceNumber))
    +      if (processorOpt.isDefined) {
    +        val processor = processorOpt.get
    +        processor.resultQueueUpdateLock.lock()
    +        try {
    +          // Is the sequence number the same as the one the processor is processing? If not,
    +          // don't update {
    +          if (processor.eventBatch.getSequenceNumber.equals(sequenceNumber)) {
    +            processor.resultQueue.put(success)
    +          }
    +        } finally {
    +          processor.resultQueueUpdateLock.unlock()
    +        }
    +      }
    +    }
    +  }
    +
    +  // Flume forces transactions to be thread-local (horrible, I know!)
    +  // So the sink basically spawns a new thread to pull the events out within a transaction.
    +  // The thread fills in the event batch object that is set before the thread is scheduled.
    +  // After filling it in, the thread waits on a condition - which is released only
    +  // when the success message comes back for the specific sequence number for that event batch.
    +  /**
    +   * This class represents a transaction on the Flume channel. This class runs a separate thread
    +   * which owns the transaction. It is blocked until the success call for that transaction comes
    +   * back.
    +   * @param maxBatchSize
    +   */
    +  private class TransactionProcessor(var maxBatchSize: Int) extends Callable[Void] {
    +    // Must be set to a new event batch before scheduling this!!
    +    val eventBatch = new EventBatch("", new util.LinkedList[SparkSinkEvent])
    +    val eventQueue = new SynchronousQueue[EventBatch]()
    +    val resultQueue = new SynchronousQueue[Boolean]()
    +    val resultQueueUpdateLock = new ReentrantLock()
    +
    +    object Zero {
    +      val zero = "0" // Oh, I miss static finals
    +    }
    +
    +
    +    override def call(): Void = {
    +      val tx = getChannel.getTransaction
    +      tx.begin()
    +      try {
    +        eventBatch.setSequenceNumber(seqBase + seqNum.incrementAndGet())
    +        val events = eventBatch.getEventBatch
    +        events.clear()
    +        val loop = new Breaks
    +        var gotEventsInThisTxn = false
    +        loop.breakable {
    +          var i = 0
    +          // Using for here causes the maxBatchSize change to be ineffective as the Range gets
    +          // pregenerated
    +          while (i < maxBatchSize) {
    +            i += 1
    +            val eventOpt = Option(getChannel.take())
    +            eventOpt.map(event => {
    --- End diff --
    
    These few lines can be formatted better (more Scala-like) as 
    ```
    Option(getChannel.take()) match {
                  case Some(event) =>
                    val headers = toCharSequenceMap(event.getHeaders)
                    val body = ByteBuffer.wrap(event.getBody)
                    events.add(new SparkSinkEvent(headers, body))
                    gotEventsInThisTxn = true
    
                  case None =>
                    if (!gotEventsInThisTxn) {
                      if (maxBatchSize >= Int.MaxValue / 2) {
                        // Random sanity check
                        throw new RuntimeException("Safety exception - polled too many times, no events!")
                      }
                      maxBatchSize += 1
                      Thread.sleep(500)
                    } else {
                      loop.break()
                    }
                }
    ```


---
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 infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] spark pull request: SPARK-1729. Make Flume pull data from source, ...

Posted by harishreedharan <gi...@git.apache.org>.
Github user harishreedharan commented on the pull request:

    https://github.com/apache/spark/pull/807#issuecomment-46398801
  
    @tdas Use the following configuration file to start flume:
    
    agent.sources = seqGenSrc
    agent.channels = memoryChannel
    agent.sinks = spark
    
    # For each one of the sources, the type is defined
    agent.sources.seqGenSrc.type = seq
    
    # The channel can be defined as follows.
    agent.sources.seqGenSrc.channels = memoryChannel
    
    # Each sink's type must be defined
    agent.sinks.spark.type = org.apache.spark.flume.sink.SparkSink
    agent.sinks.spark.hostname = 0.0.0.0
    agent.sinks.spark.port = 9999
    
    #Specify the channel the sink should use
    agent.sinks.spark.channel = memoryChannel
    
    # Each channel's type is defined.
    agent.channels.memoryChannel.type = memory
    
    # Other config values specific to each type of channel(sink or source)
    # can be defined as well
    # In this case, it specifies the capacity of the memory channel
    agent.channels.memoryChannel.capacity = 100
    
    You can start the flume agent by downloading the latest release binary tarball (or checking it out and building it), and running this command from the top level:
    bin/flume-ng agent -n agent -f <path/to/config/file> -c conf
    
    (Make sure you drop the spark-streaming-flume-sink_2.10-1.0.0-SNAPSHOT.jar from the target directory (mvn build generates this one, not sure how to get this with sbt) and scala-library.jar in the lib directory under the flume top-level directory.
    
    On the spark side, you can start a streaming application by mimicking the FlumePollingReceiverSuite class (FlumeUtils has a couple methods to start the receiver).


---
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 infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] spark pull request: SPARK-1729. Make Flume pull data from source, ...

Posted by harishreedharan <gi...@git.apache.org>.
Github user harishreedharan commented on a diff in the pull request:

    https://github.com/apache/spark/pull/807#discussion_r13473354
  
    --- Diff: external/flume-sink/src/main/scala/org/apache/spark/flume/sink/SparkSink.scala ---
    @@ -0,0 +1,392 @@
    +/*
    + * 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.flume.sink
    +
    +import org.apache.flume.sink.AbstractSink
    +import java.util.concurrent.locks.ReentrantLock
    +import org.apache.flume.Sink.Status
    +import org.apache.spark.flume.{SparkSinkEvent, EventBatch, SparkFlumeProtocol}
    +import scala.util.control.Breaks
    +import java.nio.ByteBuffer
    +import org.apache.flume.{FlumeException, Context}
    +import org.slf4j.LoggerFactory
    +import java.util.concurrent.atomic.AtomicLong
    +import org.apache.commons.lang.RandomStringUtils
    +import java.util.concurrent._
    +import java.util
    +import org.apache.flume.conf.{ConfigurationException, Configurable}
    +import com.google.common.util.concurrent.ThreadFactoryBuilder
    +import org.apache.avro.ipc.NettyServer
    +import org.apache.avro.ipc.specific.SpecificResponder
    +import java.net.InetSocketAddress
    +
    +class SparkSink() extends AbstractSink with Configurable {
    +  private val LOG = LoggerFactory.getLogger(this.getClass)
    +  private val lock = new ReentrantLock()
    +  private val blockingCondition = lock.newCondition()
    +
    +  // This sink will not persist sequence numbers and reuses them if it gets restarted.
    +  // So it is possible to commit a transaction which may have been meant for the sink before the
    +  // restart.
    +  // Since the new txn may not have the same sequence number we must guard against accidentally
    +  // committing
    +  // a new transaction. To reduce the probability of that happening a random string is prepended
    +  // to the sequence number.
    +  // Does not change for life of sink
    +  private val seqBase = RandomStringUtils.randomAlphanumeric(8)
    +  // Incremented for each transaction
    +  private val seqNum = new AtomicLong(0)
    +
    +  private var transactionExecutorOpt: Option[ExecutorService] = None
    +
    +  private var numProcessors: Integer = SparkSinkConfig.DEFAULT_PROCESSOR_COUNT
    +  private var transactionTimeout = SparkSinkConfig.DEFAULT_TRANSACTION_TIMEOUT
    +
    +  private val processorMap = new ConcurrentHashMap[CharSequence, TransactionProcessor]()
    +
    +  private var processorFactory: Option[SparkHandlerFactory] = None
    +  private var hostname: String = SparkSinkConfig.DEFAULT_HOSTNAME
    +  private var port: Int = 0
    +  private var maxThreads: Int = SparkSinkConfig.DEFAULT_MAX_THREADS
    +  private var serverOpt: Option[NettyServer] = None
    +  private var running = false
    +
    +  override def start() {
    +    transactionExecutorOpt = Option(Executors.newFixedThreadPool(numProcessors,
    +      new ThreadFactoryBuilder().setDaemon(true)
    +        .setNameFormat("Spark Sink, " + getName + " Processor Thread - %d").build()))
    +
    +    processorFactory = Option(new SparkHandlerFactory(numProcessors))
    +
    +    val responder = new SpecificResponder(classOf[SparkFlumeProtocol], new AvroCallbackHandler())
    +
    +    // Using the constructor that takes specific thread-pools requires bringing in netty
    +    // dependencies which are being excluded in the build. In practice,
    +    // Netty dependencies are already available on the JVM as Flume would have pulled them in.
    +    serverOpt = Option(new NettyServer(responder, new InetSocketAddress(hostname, port)))
    +
    +    serverOpt.map(server => server.start())
    +    lock.lock()
    +    try {
    +      running = true
    +    } finally {
    +      lock.unlock()
    +    }
    +    super.start()
    +  }
    +
    +  override def stop() {
    +    transactionExecutorOpt.map(executor => executor.shutdownNow())
    +    serverOpt.map(server => {
    +      server.close()
    +      server.join()
    +    })
    +    lock.lock()
    +    try {
    +      running = false
    +      blockingCondition.signalAll()
    +    } finally {
    +      lock.unlock()
    +    }
    +  }
    +
    +  override def configure(ctx: Context) {
    +    import SparkSinkConfig._
    +    hostname = ctx.getString(CONF_HOSTNAME, DEFAULT_HOSTNAME)
    +    val portOpt = Option(ctx.getInteger(CONF_PORT))
    +    if(portOpt.isDefined) {
    +      port = portOpt.get
    +    } else {
    +      throw new ConfigurationException("The Port to bind must be specified")
    +    }
    +    numProcessors = ctx.getInteger(PROCESSOR_COUNT, DEFAULT_PROCESSOR_COUNT)
    +    transactionTimeout = ctx.getInteger(CONF_TRANSACTION_TIMEOUT, DEFAULT_TRANSACTION_TIMEOUT)
    +    maxThreads = ctx.getInteger(CONF_MAX_THREADS, DEFAULT_MAX_THREADS)
    +  }
    +
    +  override def process(): Status = {
    +    // This method is called in a loop by the Flume framework - block it until the sink is
    +    // stopped to save CPU resources
    +    lock.lock()
    +    try {
    +      while(running) {
    --- End diff --
    
    The reason we can't use CountdownLatch (I actually considered this) is that the thread could be interrupted in some cases in Flume, in which case Flume will call process method again, so we'd need to allocate a new CountdownLatch (I don't think it has a reset option).


---
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 infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] spark pull request: SPARK-1729. Make Flume pull data from source, ...

Posted by harishreedharan <gi...@git.apache.org>.
Github user harishreedharan commented on a diff in the pull request:

    https://github.com/apache/spark/pull/807#discussion_r13426044
  
    --- Diff: external/flume-sink/src/main/scala/org/apache/spark/flume/sink/SparkSink.scala ---
    @@ -0,0 +1,392 @@
    +/*
    + * 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.flume.sink
    +
    +import org.apache.flume.sink.AbstractSink
    --- End diff --
    
    Thanks! I will fix this


---
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 infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] spark pull request: SPARK-1729. Make Flume pull data from source, ...

Posted by harishreedharan <gi...@git.apache.org>.
Github user harishreedharan commented on the pull request:

    https://github.com/apache/spark/pull/807#issuecomment-46806458
  
    @tdas - Have you gotten a chance to take a look at this? Thanks!


---
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 infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] spark pull request: [STREAMING] SPARK-1729. Make Flume pull data f...

Posted by tdas <gi...@git.apache.org>.
Github user tdas commented on the pull request:

    https://github.com/apache/spark/pull/807#issuecomment-50414891
  
    All right! Merging this!
    THIS WAS A LOT OF WORK. THANK YOU VERY MUCH!


---
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 infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] spark pull request: [STREAMING] SPARK-1729. Make Flume pull data f...

Posted by SparkQA <gi...@git.apache.org>.
Github user SparkQA commented on the pull request:

    https://github.com/apache/spark/pull/807#issuecomment-50401698
  
    QA results for PR 807:<br>- This patch PASSES unit tests.<br>- This patch merges cleanly<br>- This patch adds the following public classes (experimental):<br>class SparkSink extends AbstractSink with Logging with Configurable {<br><br>For more information see test ouptut:<br>https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/17303/consoleFull


---
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 infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] spark pull request: SPARK-1729. Make Flume pull data from source, ...

Posted by tdas <gi...@git.apache.org>.
Github user tdas commented on a diff in the pull request:

    https://github.com/apache/spark/pull/807#discussion_r13463876
  
    --- Diff: external/flume-sink/src/main/scala/org/apache/spark/flume/sink/SparkSink.scala ---
    @@ -0,0 +1,392 @@
    +/*
    + * 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.flume.sink
    +
    +import org.apache.flume.sink.AbstractSink
    +import java.util.concurrent.locks.ReentrantLock
    +import org.apache.flume.Sink.Status
    +import org.apache.spark.flume.{SparkSinkEvent, EventBatch, SparkFlumeProtocol}
    +import scala.util.control.Breaks
    +import java.nio.ByteBuffer
    +import org.apache.flume.{FlumeException, Context}
    +import org.slf4j.LoggerFactory
    +import java.util.concurrent.atomic.AtomicLong
    +import org.apache.commons.lang.RandomStringUtils
    +import java.util.concurrent._
    +import java.util
    +import org.apache.flume.conf.{ConfigurationException, Configurable}
    +import com.google.common.util.concurrent.ThreadFactoryBuilder
    +import org.apache.avro.ipc.NettyServer
    +import org.apache.avro.ipc.specific.SpecificResponder
    +import java.net.InetSocketAddress
    +
    +class SparkSink() extends AbstractSink with Configurable {
    +  private val LOG = LoggerFactory.getLogger(this.getClass)
    +  private val lock = new ReentrantLock()
    +  private val blockingCondition = lock.newCondition()
    +
    +  // This sink will not persist sequence numbers and reuses them if it gets restarted.
    +  // So it is possible to commit a transaction which may have been meant for the sink before the
    +  // restart.
    +  // Since the new txn may not have the same sequence number we must guard against accidentally
    +  // committing
    +  // a new transaction. To reduce the probability of that happening a random string is prepended
    +  // to the sequence number.
    +  // Does not change for life of sink
    +  private val seqBase = RandomStringUtils.randomAlphanumeric(8)
    +  // Incremented for each transaction
    +  private val seqNum = new AtomicLong(0)
    +
    +  private var transactionExecutorOpt: Option[ExecutorService] = None
    +
    +  private var numProcessors: Integer = SparkSinkConfig.DEFAULT_PROCESSOR_COUNT
    +  private var transactionTimeout = SparkSinkConfig.DEFAULT_TRANSACTION_TIMEOUT
    +
    +  private val processorMap = new ConcurrentHashMap[CharSequence, TransactionProcessor]()
    +
    +  private var processorFactory: Option[SparkHandlerFactory] = None
    +  private var hostname: String = SparkSinkConfig.DEFAULT_HOSTNAME
    +  private var port: Int = 0
    +  private var maxThreads: Int = SparkSinkConfig.DEFAULT_MAX_THREADS
    +  private var serverOpt: Option[NettyServer] = None
    +  private var running = false
    +
    +  override def start() {
    +    transactionExecutorOpt = Option(Executors.newFixedThreadPool(numProcessors,
    +      new ThreadFactoryBuilder().setDaemon(true)
    +        .setNameFormat("Spark Sink, " + getName + " Processor Thread - %d").build()))
    +
    +    processorFactory = Option(new SparkHandlerFactory(numProcessors))
    +
    +    val responder = new SpecificResponder(classOf[SparkFlumeProtocol], new AvroCallbackHandler())
    +
    +    // Using the constructor that takes specific thread-pools requires bringing in netty
    +    // dependencies which are being excluded in the build. In practice,
    +    // Netty dependencies are already available on the JVM as Flume would have pulled them in.
    +    serverOpt = Option(new NettyServer(responder, new InetSocketAddress(hostname, port)))
    +
    +    serverOpt.map(server => server.start())
    +    lock.lock()
    +    try {
    +      running = true
    +    } finally {
    +      lock.unlock()
    +    }
    +    super.start()
    +  }
    +
    +  override def stop() {
    +    transactionExecutorOpt.map(executor => executor.shutdownNow())
    +    serverOpt.map(server => {
    +      server.close()
    +      server.join()
    +    })
    +    lock.lock()
    +    try {
    +      running = false
    +      blockingCondition.signalAll()
    +    } finally {
    +      lock.unlock()
    +    }
    +  }
    +
    +  override def configure(ctx: Context) {
    +    import SparkSinkConfig._
    +    hostname = ctx.getString(CONF_HOSTNAME, DEFAULT_HOSTNAME)
    +    val portOpt = Option(ctx.getInteger(CONF_PORT))
    +    if(portOpt.isDefined) {
    +      port = portOpt.get
    +    } else {
    +      throw new ConfigurationException("The Port to bind must be specified")
    +    }
    +    numProcessors = ctx.getInteger(PROCESSOR_COUNT, DEFAULT_PROCESSOR_COUNT)
    +    transactionTimeout = ctx.getInteger(CONF_TRANSACTION_TIMEOUT, DEFAULT_TRANSACTION_TIMEOUT)
    +    maxThreads = ctx.getInteger(CONF_MAX_THREADS, DEFAULT_MAX_THREADS)
    +  }
    +
    +  override def process(): Status = {
    +    // This method is called in a loop by the Flume framework - block it until the sink is
    +    // stopped to save CPU resources
    +    lock.lock()
    +    try {
    +      while(running) {
    +        blockingCondition.await()
    +      }
    +    } finally {
    +      lock.unlock()
    +    }
    +    Status.BACKOFF
    +  }
    +
    +
    +  // Object representing an empty batch returned by the txn processor due to some error.
    +  case object ErrorEventBatch extends EventBatch
    +
    +  private class AvroCallbackHandler() extends SparkFlumeProtocol {
    +
    +    override def getEventBatch(n: Int): EventBatch = {
    +      val processor = processorFactory.get.checkOut(n)
    +      transactionExecutorOpt.map(executor => executor.submit(processor))
    +      // Wait until a batch is available - can be null if some error was thrown
    +      val eventBatch = processor.eventQueue.take()
    +      eventBatch match {
    +        case ErrorEventBatch => throw new FlumeException("Something went wrong. No events" +
    +          " retrieved from channel.")
    +        case events => {
    +          processorMap.put(events.getSequenceNumber, processor)
    +          if (LOG.isDebugEnabled) {
    +            LOG.debug("Sent " + events.getEventBatch.size() +
    +              " events with sequence number: " + events.getSequenceNumber)
    +          }
    +          events
    +        }
    +      }
    +    }
    +
    +    override def ack(sequenceNumber: CharSequence): Void = {
    +      completeTransaction(sequenceNumber, success = true)
    +      null
    +    }
    +
    +    override def nack(sequenceNumber: CharSequence): Void = {
    +      completeTransaction(sequenceNumber, success = false)
    +      LOG.info("Spark failed to commit transaction. Will reattempt events.")
    +      null
    +    }
    +
    +    def completeTransaction(sequenceNumber: CharSequence, success: Boolean) {
    +      val processorOpt = Option(processorMap.remove(sequenceNumber))
    +      if (processorOpt.isDefined) {
    +        val processor = processorOpt.get
    +        processor.resultQueueUpdateLock.lock()
    +        try {
    +          // Is the sequence number the same as the one the processor is processing? If not,
    +          // don't update {
    +          if (processor.eventBatch.getSequenceNumber.equals(sequenceNumber)) {
    +            processor.resultQueue.put(success)
    +          }
    +        } finally {
    +          processor.resultQueueUpdateLock.unlock()
    +        }
    +      }
    +    }
    +  }
    +
    +  // Flume forces transactions to be thread-local (horrible, I know!)
    +  // So the sink basically spawns a new thread to pull the events out within a transaction.
    +  // The thread fills in the event batch object that is set before the thread is scheduled.
    +  // After filling it in, the thread waits on a condition - which is released only
    +  // when the success message comes back for the specific sequence number for that event batch.
    +  /**
    +   * This class represents a transaction on the Flume channel. This class runs a separate thread
    +   * which owns the transaction. It is blocked until the success call for that transaction comes
    +   * back.
    +   * @param maxBatchSize
    +   */
    +  private class TransactionProcessor(var maxBatchSize: Int) extends Callable[Void] {
    +    // Must be set to a new event batch before scheduling this!!
    +    val eventBatch = new EventBatch("", new util.LinkedList[SparkSinkEvent])
    +    val eventQueue = new SynchronousQueue[EventBatch]()
    +    val resultQueue = new SynchronousQueue[Boolean]()
    +    val resultQueueUpdateLock = new ReentrantLock()
    +
    +    object Zero {
    +      val zero = "0" // Oh, I miss static finals
    +    }
    +
    +
    +    override def call(): Void = {
    +      val tx = getChannel.getTransaction
    +      tx.begin()
    +      try {
    +        eventBatch.setSequenceNumber(seqBase + seqNum.incrementAndGet())
    +        val events = eventBatch.getEventBatch
    +        events.clear()
    +        val loop = new Breaks
    +        var gotEventsInThisTxn = false
    +        loop.breakable {
    +          var i = 0
    +          // Using for here causes the maxBatchSize change to be ineffective as the Range gets
    +          // pregenerated
    +          while (i < maxBatchSize) {
    +            i += 1
    +            val eventOpt = Option(getChannel.take())
    +            eventOpt.map(event => {
    +              events.add(new SparkSinkEvent(toCharSequenceMap(event
    +                .getHeaders),
    +                ByteBuffer.wrap(event.getBody)))
    +              gotEventsInThisTxn = true
    +            })
    +            if (eventOpt.isEmpty) {
    +              if (!gotEventsInThisTxn) {
    +                // To avoid sending empty batches, we wait till events are available backing off
    +                // between attempts to get events. Each attempt to get an event though causes one
    +                // iteration to be lost. To ensure that we still send back maxBatchSize number of
    +                // events, we cheat and increase the maxBatchSize by 1 to account for the lost
    +                // iteration. Even throwing an exception is expensive as Avro will serialize it
    +                // and send it over the wire, which is useless. Before incrementing though,
    +                // ensure that we are not anywhere near INT_MAX.
    +                if (maxBatchSize >= Int.MaxValue / 2) {
    --- End diff --
    
    Why increase `maxBatchSize` and handle corner cases like `Int.MaxValue / 2` ? Isnt it rather more intuitive to run the loop till while `events.size() < maxBatchSize`?


---
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 infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] spark pull request: SPARK-1729. Make Flume pull data from source, ...

Posted by tdas <gi...@git.apache.org>.
Github user tdas commented on a diff in the pull request:

    https://github.com/apache/spark/pull/807#discussion_r13473226
  
    --- Diff: external/flume-sink/src/main/scala/org/apache/spark/flume/sink/SparkSink.scala ---
    @@ -0,0 +1,392 @@
    +/*
    + * 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.flume.sink
    +
    +import org.apache.flume.sink.AbstractSink
    +import java.util.concurrent.locks.ReentrantLock
    +import org.apache.flume.Sink.Status
    +import org.apache.spark.flume.{SparkSinkEvent, EventBatch, SparkFlumeProtocol}
    +import scala.util.control.Breaks
    +import java.nio.ByteBuffer
    +import org.apache.flume.{FlumeException, Context}
    +import org.slf4j.LoggerFactory
    +import java.util.concurrent.atomic.AtomicLong
    +import org.apache.commons.lang.RandomStringUtils
    +import java.util.concurrent._
    +import java.util
    +import org.apache.flume.conf.{ConfigurationException, Configurable}
    +import com.google.common.util.concurrent.ThreadFactoryBuilder
    +import org.apache.avro.ipc.NettyServer
    +import org.apache.avro.ipc.specific.SpecificResponder
    +import java.net.InetSocketAddress
    +
    +class SparkSink() extends AbstractSink with Configurable {
    +  private val LOG = LoggerFactory.getLogger(this.getClass)
    +  private val lock = new ReentrantLock()
    +  private val blockingCondition = lock.newCondition()
    +
    +  // This sink will not persist sequence numbers and reuses them if it gets restarted.
    +  // So it is possible to commit a transaction which may have been meant for the sink before the
    +  // restart.
    +  // Since the new txn may not have the same sequence number we must guard against accidentally
    +  // committing
    +  // a new transaction. To reduce the probability of that happening a random string is prepended
    +  // to the sequence number.
    +  // Does not change for life of sink
    +  private val seqBase = RandomStringUtils.randomAlphanumeric(8)
    +  // Incremented for each transaction
    +  private val seqNum = new AtomicLong(0)
    +
    +  private var transactionExecutorOpt: Option[ExecutorService] = None
    +
    +  private var numProcessors: Integer = SparkSinkConfig.DEFAULT_PROCESSOR_COUNT
    +  private var transactionTimeout = SparkSinkConfig.DEFAULT_TRANSACTION_TIMEOUT
    +
    +  private val processorMap = new ConcurrentHashMap[CharSequence, TransactionProcessor]()
    +
    +  private var processorFactory: Option[SparkHandlerFactory] = None
    +  private var hostname: String = SparkSinkConfig.DEFAULT_HOSTNAME
    +  private var port: Int = 0
    +  private var maxThreads: Int = SparkSinkConfig.DEFAULT_MAX_THREADS
    +  private var serverOpt: Option[NettyServer] = None
    +  private var running = false
    +
    +  override def start() {
    +    transactionExecutorOpt = Option(Executors.newFixedThreadPool(numProcessors,
    +      new ThreadFactoryBuilder().setDaemon(true)
    +        .setNameFormat("Spark Sink, " + getName + " Processor Thread - %d").build()))
    +
    +    processorFactory = Option(new SparkHandlerFactory(numProcessors))
    +
    +    val responder = new SpecificResponder(classOf[SparkFlumeProtocol], new AvroCallbackHandler())
    +
    +    // Using the constructor that takes specific thread-pools requires bringing in netty
    +    // dependencies which are being excluded in the build. In practice,
    +    // Netty dependencies are already available on the JVM as Flume would have pulled them in.
    +    serverOpt = Option(new NettyServer(responder, new InetSocketAddress(hostname, port)))
    +
    +    serverOpt.map(server => server.start())
    +    lock.lock()
    +    try {
    +      running = true
    +    } finally {
    +      lock.unlock()
    +    }
    +    super.start()
    +  }
    +
    +  override def stop() {
    --- End diff --
    
    Are start() and stop() guaranteed to be not called by Flume in concurrently? If that is not the case, these probably should be synchronized.


---
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 infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] spark pull request: SPARK-1729. Make Flume pull data from source, ...

Posted by tdas <gi...@git.apache.org>.
Github user tdas commented on a diff in the pull request:

    https://github.com/apache/spark/pull/807#discussion_r13455872
  
    --- Diff: external/flume/src/main/scala/org/apache/spark/streaming/flume/FlumePollingInputDStream.scala ---
    @@ -0,0 +1,165 @@
    +/*
    + * 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.streaming.flume
    +
    +
    +import java.io.{ObjectOutput, ObjectInput, Externalizable}
    +import java.net.InetSocketAddress
    +import java.nio.ByteBuffer
    +import java.util.concurrent.{TimeUnit, Executors}
    +
    +import scala.collection.JavaConversions._
    +import scala.collection.mutable
    +import scala.reflect.ClassTag
    +
    +import com.google.common.util.concurrent.ThreadFactoryBuilder
    +import org.apache.avro.ipc.NettyTransceiver
    +import org.apache.avro.ipc.specific.SpecificRequestor
    +import org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory
    +
    +import org.apache.spark.Logging
    +import org.apache.spark.flume.{SparkSinkEvent, SparkFlumeProtocol}
    +import org.apache.spark.storage.StorageLevel
    +import org.apache.spark.streaming.StreamingContext
    +import org.apache.spark.streaming.dstream.ReceiverInputDStream
    +import org.apache.spark.streaming.receiver.Receiver
    +
    +
    +
    +class FlumePollingInputDStream[T: ClassTag](
    +  @transient ssc_ : StreamingContext,
    +  val addresses: Seq[InetSocketAddress],
    +  val maxBatchSize: Int,
    +  val parallelism: Int,
    +  storageLevel: StorageLevel
    +) extends ReceiverInputDStream[SparkPollingEvent](ssc_) {
    +  /**
    +   * Gets the receiver object that will be sent to the worker nodes
    +   * to receive data. This method needs to defined by any specific implementation
    +   * of a NetworkInputDStream.
    +   */
    +  override def getReceiver(): Receiver[SparkPollingEvent] = {
    +    new FlumePollingReceiver(addresses, maxBatchSize, parallelism, storageLevel)
    +  }
    +}
    +
    +private[streaming] class FlumePollingReceiver(
    +  addresses: Seq[InetSocketAddress],
    +  maxBatchSize: Int,
    +  parallelism: Int,
    +  storageLevel: StorageLevel
    +) extends Receiver[SparkPollingEvent](storageLevel) with Logging {
    +
    +  lazy val channelFactoryExecutor =
    +    Executors.newCachedThreadPool(new ThreadFactoryBuilder().setDaemon(true).
    +      setNameFormat("Flume Receiver Channel Thread - %d").build())
    +
    +  lazy val channelFactory =
    +    new NioClientSocketChannelFactory(channelFactoryExecutor, channelFactoryExecutor)
    +
    +  lazy val receiverExecutor = Executors.newFixedThreadPool(parallelism,
    +    new ThreadFactoryBuilder().setDaemon(true).setNameFormat("Flume Receiver Thread - %d").build())
    +
    +  private var connections = Array.empty[FlumeConnection] // temporarily empty, filled in later
    +
    +  override def onStart(): Unit = {
    +    val connectionBuilder = new mutable.ArrayBuilder.ofRef[FlumeConnection]()
    +    addresses.map(host => {
    +      val transceiver = new NettyTransceiver(host, channelFactory)
    +      val client = SpecificRequestor.getClient(classOf[SparkFlumeProtocol.Callback], transceiver)
    +      connectionBuilder += new FlumeConnection(transceiver, client)
    +    })
    +    connections = connectionBuilder.result()
    --- End diff --
    
    `connections` could be built in a more Scala-like functional style. Something like this.
    ```
    connections = addresses.map { host =>  .....   new FlumeConnection(....) }.toArray
    ```
    
    No need for ArrayBuilder 


---
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 infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] spark pull request: SPARK-1729. Make Flume pull data from source, ...

Posted by tdas <gi...@git.apache.org>.
Github user tdas commented on a diff in the pull request:

    https://github.com/apache/spark/pull/807#discussion_r13466881
  
    --- Diff: external/flume-sink/src/main/scala/org/apache/spark/flume/sink/SparkSink.scala ---
    @@ -0,0 +1,392 @@
    +/*
    + * 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.flume.sink
    +
    +import org.apache.flume.sink.AbstractSink
    +import java.util.concurrent.locks.ReentrantLock
    +import org.apache.flume.Sink.Status
    +import org.apache.spark.flume.{SparkSinkEvent, EventBatch, SparkFlumeProtocol}
    +import scala.util.control.Breaks
    +import java.nio.ByteBuffer
    +import org.apache.flume.{FlumeException, Context}
    +import org.slf4j.LoggerFactory
    +import java.util.concurrent.atomic.AtomicLong
    +import org.apache.commons.lang.RandomStringUtils
    +import java.util.concurrent._
    +import java.util
    +import org.apache.flume.conf.{ConfigurationException, Configurable}
    +import com.google.common.util.concurrent.ThreadFactoryBuilder
    +import org.apache.avro.ipc.NettyServer
    +import org.apache.avro.ipc.specific.SpecificResponder
    +import java.net.InetSocketAddress
    +
    +class SparkSink() extends AbstractSink with Configurable {
    +  private val LOG = LoggerFactory.getLogger(this.getClass)
    +  private val lock = new ReentrantLock()
    +  private val blockingCondition = lock.newCondition()
    +
    +  // This sink will not persist sequence numbers and reuses them if it gets restarted.
    +  // So it is possible to commit a transaction which may have been meant for the sink before the
    +  // restart.
    +  // Since the new txn may not have the same sequence number we must guard against accidentally
    +  // committing
    +  // a new transaction. To reduce the probability of that happening a random string is prepended
    +  // to the sequence number.
    +  // Does not change for life of sink
    +  private val seqBase = RandomStringUtils.randomAlphanumeric(8)
    +  // Incremented for each transaction
    +  private val seqNum = new AtomicLong(0)
    +
    +  private var transactionExecutorOpt: Option[ExecutorService] = None
    +
    +  private var numProcessors: Integer = SparkSinkConfig.DEFAULT_PROCESSOR_COUNT
    +  private var transactionTimeout = SparkSinkConfig.DEFAULT_TRANSACTION_TIMEOUT
    +
    +  private val processorMap = new ConcurrentHashMap[CharSequence, TransactionProcessor]()
    +
    +  private var processorFactory: Option[SparkHandlerFactory] = None
    +  private var hostname: String = SparkSinkConfig.DEFAULT_HOSTNAME
    +  private var port: Int = 0
    +  private var maxThreads: Int = SparkSinkConfig.DEFAULT_MAX_THREADS
    +  private var serverOpt: Option[NettyServer] = None
    +  private var running = false
    +
    +  override def start() {
    +    transactionExecutorOpt = Option(Executors.newFixedThreadPool(numProcessors,
    +      new ThreadFactoryBuilder().setDaemon(true)
    +        .setNameFormat("Spark Sink, " + getName + " Processor Thread - %d").build()))
    +
    +    processorFactory = Option(new SparkHandlerFactory(numProcessors))
    +
    +    val responder = new SpecificResponder(classOf[SparkFlumeProtocol], new AvroCallbackHandler())
    +
    +    // Using the constructor that takes specific thread-pools requires bringing in netty
    +    // dependencies which are being excluded in the build. In practice,
    +    // Netty dependencies are already available on the JVM as Flume would have pulled them in.
    +    serverOpt = Option(new NettyServer(responder, new InetSocketAddress(hostname, port)))
    +
    +    serverOpt.map(server => server.start())
    +    lock.lock()
    +    try {
    +      running = true
    +    } finally {
    +      lock.unlock()
    +    }
    +    super.start()
    +  }
    +
    +  override def stop() {
    +    transactionExecutorOpt.map(executor => executor.shutdownNow())
    +    serverOpt.map(server => {
    +      server.close()
    +      server.join()
    +    })
    +    lock.lock()
    +    try {
    +      running = false
    +      blockingCondition.signalAll()
    +    } finally {
    +      lock.unlock()
    +    }
    +  }
    +
    +  override def configure(ctx: Context) {
    +    import SparkSinkConfig._
    +    hostname = ctx.getString(CONF_HOSTNAME, DEFAULT_HOSTNAME)
    +    val portOpt = Option(ctx.getInteger(CONF_PORT))
    +    if(portOpt.isDefined) {
    +      port = portOpt.get
    +    } else {
    +      throw new ConfigurationException("The Port to bind must be specified")
    +    }
    +    numProcessors = ctx.getInteger(PROCESSOR_COUNT, DEFAULT_PROCESSOR_COUNT)
    +    transactionTimeout = ctx.getInteger(CONF_TRANSACTION_TIMEOUT, DEFAULT_TRANSACTION_TIMEOUT)
    +    maxThreads = ctx.getInteger(CONF_MAX_THREADS, DEFAULT_MAX_THREADS)
    +  }
    +
    +  override def process(): Status = {
    +    // This method is called in a loop by the Flume framework - block it until the sink is
    +    // stopped to save CPU resources
    +    lock.lock()
    +    try {
    +      while(running) {
    --- End diff --
    
    If this just needs to stay blocked until stopped, then why isnt just the `blockingCondition.await()` enough? Why is the while loop necessary?


---
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 infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] spark pull request: SPARK-1729. Make Flume pull data from source, ...

Posted by harishreedharan <gi...@git.apache.org>.
Github user harishreedharan commented on a diff in the pull request:

    https://github.com/apache/spark/pull/807#discussion_r12802518
  
    --- Diff: external/flume-sink/src/main/scala/org/apache/spark/flume/sink/SparkSink.scala ---
    @@ -0,0 +1,392 @@
    +/*
    + * 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.flume.sink
    +
    +import org.apache.flume.sink.AbstractSink
    +import java.util.concurrent.locks.ReentrantLock
    +import org.apache.flume.Sink.Status
    +import org.apache.spark.flume.{SparkSinkEvent, EventBatch, SparkFlumeProtocol}
    +import scala.util.control.Breaks
    +import java.nio.ByteBuffer
    +import org.apache.flume.{FlumeException, Context}
    +import org.slf4j.LoggerFactory
    +import java.util.concurrent.atomic.AtomicLong
    +import org.apache.commons.lang.RandomStringUtils
    +import java.util.concurrent._
    +import java.util
    +import org.apache.flume.conf.{ConfigurationException, Configurable}
    +import com.google.common.util.concurrent.ThreadFactoryBuilder
    +import org.apache.avro.ipc.NettyServer
    +import org.apache.avro.ipc.specific.SpecificResponder
    +import java.net.InetSocketAddress
    +
    +class SparkSink() extends AbstractSink with Configurable {
    +  private val LOG = LoggerFactory.getLogger(this.getClass)
    +  private val lock = new ReentrantLock()
    +  private val blockingCondition = lock.newCondition()
    --- End diff --
    
    In some JVMs, locks perform better than synchronized. Also, I feel conditionals are clearer than wait/notify. In this case, I am using the lock only for the conditional.


---
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 infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] spark pull request: SPARK-1729. Make Flume pull data from source, ...

Posted by harishreedharan <gi...@git.apache.org>.
Github user harishreedharan commented on a diff in the pull request:

    https://github.com/apache/spark/pull/807#discussion_r13835087
  
    --- Diff: external/flume-sink/src/main/scala/org/apache/spark/flume/sink/SparkSink.scala ---
    @@ -0,0 +1,432 @@
    +/*
    + * 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.flume.sink
    +
    +import java.net.InetSocketAddress
    +import java.nio.ByteBuffer
    +import java.util
    +import java.util.concurrent._
    +import java.util.concurrent.atomic.AtomicLong
    +
    +import scala.util.control.Breaks
    +
    +import com.google.common.util.concurrent.ThreadFactoryBuilder
    +import org.apache.avro.ipc.NettyServer
    +import org.apache.avro.ipc.specific.SpecificResponder
    +import org.apache.commons.lang.RandomStringUtils
    +import org.apache.flume.Sink.Status
    +import org.apache.flume.conf.{ConfigurationException, Configurable}
    +import org.apache.flume.sink.AbstractSink
    +import org.apache.flume.{Channel, Transaction, FlumeException, Context}
    +import org.slf4j.LoggerFactory
    +
    +import org.apache.spark.flume.{SparkSinkEvent, EventBatch, SparkFlumeProtocol}
    +
    +/**
    + * A sink that uses Avro RPC to run a server that can be polled by Spark's
    + * FlumePollingInputDStream. This sink has the following configuration parameters:
    + *
    + * hostname - The hostname to bind to. Default: 0.0.0.0
    + * port - The port to bind to. (No default - mandatory)
    + * timeout - Time in seconds after which a transaction is rolled back,
    + * if an ACK is not received from Spark within that time
    + * threads - Number of threads to use to receive requests from Spark (Default: 10)
    + *
    + */
    +// Flume forces transactions to be thread-local. So each transaction *must* be committed, or
    +// rolled back from the thread it was originally created in. So each getEvents call from Spark
    +// creates a TransactionProcessor which runs in a new thread, in which the transaction is created
    +// and events are pulled off the channel. Once the events are sent to spark,
    +// that thread is blocked and the TransactionProcessor is saved in a map,
    +// until an ACK or NACK comes back or the transaction times out (after the specified timeout).
    +// When the response comes, the TransactionProcessor is retrieved and then unblocked,
    +// at which point the transaction is committed or rolled back.
    +class SparkSink extends AbstractSink with Configurable {
    +
    +  // Size of the pool to use for holding transaction processors.
    +  private var poolSize: Integer = SparkSinkConfig.DEFAULT_THREADS
    +
    +  // Timeout for each transaction. If spark does not respond in this much time,
    +  // rollback the transaction
    +  private var transactionTimeout = SparkSinkConfig.DEFAULT_TRANSACTION_TIMEOUT
    +
    +  // Address info to bind on
    +  private var hostname: String = SparkSinkConfig.DEFAULT_HOSTNAME
    +  private var port: Int = 0
    +
    +  // Handle to the server
    +  private var serverOpt: Option[NettyServer] = None
    +
    +  // The handler that handles the callback from Avro
    +  private var handler: Option[SparkAvroCallbackHandler] = None
    +
    +  // Latch that blocks off the Flume framework from wasting 1 thread.
    +  private val blockingLatch = new CountDownLatch(1)
    +
    +  override def start() {
    +    handler = Option(new SparkAvroCallbackHandler(poolSize, getChannel, transactionTimeout))
    +    val responder = new SpecificResponder(classOf[SparkFlumeProtocol], handler.get)
    +    // Using the constructor that takes specific thread-pools requires bringing in netty
    +    // dependencies which are being excluded in the build. In practice,
    +    // Netty dependencies are already available on the JVM as Flume would have pulled them in.
    +    serverOpt = Option(new NettyServer(responder, new InetSocketAddress(hostname, port)))
    +    serverOpt.map(server => {
    +      server.start()
    +    })
    +    super.start()
    +  }
    +
    +  override def stop() {
    +    handler.map(callbackHandler => {
    +      callbackHandler.shutdown()
    +    })
    +    serverOpt.map(server => {
    +      server.close()
    +      server.join()
    +    })
    +    blockingLatch.countDown()
    +    super.stop()
    +  }
    +
    +  /**
    +   * @param ctx
    +   */
    +  override def configure(ctx: Context) {
    +    import SparkSinkConfig._
    +    hostname = ctx.getString(CONF_HOSTNAME, DEFAULT_HOSTNAME)
    +    port = Option(ctx.getInteger(CONF_PORT)).
    +      getOrElse(throw new ConfigurationException("The port to bind to must be specified"))
    +    poolSize = ctx.getInteger(THREADS, DEFAULT_THREADS)
    +    transactionTimeout = ctx.getInteger(CONF_TRANSACTION_TIMEOUT, DEFAULT_TRANSACTION_TIMEOUT)
    +  }
    +
    +  override def process(): Status = {
    +    // This method is called in a loop by the Flume framework - block it until the sink is
    +    // stopped to save CPU resources. The sink runner will interrupt this thread when the sink is
    +    // being shut down.
    +    blockingLatch.await()
    +    Status.BACKOFF
    +  }
    +}
    +
    +/**
    + * Class that implements the SparkFlumeProtocol, that is used by the Avro Netty Server to process
    + * requests. Each getEvents, ack and nack call is forwarded to an instance of this class.
    + * @param threads Number of threads to use to process requests.
    + * @param channel The channel that the sink pulls events from
    + * @param transactionTimeout Timeout in millis after which the transaction if not acked by Spark
    + *                           is rolled back.
    + */
    +private class SparkAvroCallbackHandler(val threads: Int, val channel: Channel,
    +  val transactionTimeout: Int) extends SparkFlumeProtocol {
    +  private val LOG = LoggerFactory.getLogger(classOf[SparkAvroCallbackHandler])
    +  val transactionExecutorOpt = Option(Executors.newFixedThreadPool(threads,
    +    new ThreadFactoryBuilder().setDaemon(true)
    +      .setNameFormat("Spark Sink Processor Thread - %d").build()))
    +  private val processorMap = new ConcurrentHashMap[CharSequence, TransactionProcessor]()
    +  // This sink will not persist sequence numbers and reuses them if it gets restarted.
    +  // So it is possible to commit a transaction which may have been meant for the sink before the
    +  // restart.
    +  // Since the new txn may not have the same sequence number we must guard against accidentally
    +  // committing a new transaction. To reduce the probability of that happening a random string is
    +  // prepended to the sequence number. Does not change for life of sink
    +  private val seqBase = RandomStringUtils.randomAlphanumeric(8)
    +  private val seqCounter = new AtomicLong(0)
    +
    +  /**
    +   * Returns a bunch of events to Spark over Avro RPC.
    +   * @param n Maximum number of events to return in a batch
    +   * @return [[EventBatch]] instance that has a sequence number and an array of at most n events
    +   */
    +  override def getEventBatch(n: Int): EventBatch = {
    +    val sequenceNumber = seqBase + seqCounter.incrementAndGet()
    +    val processor = new TransactionProcessor(channel, sequenceNumber,
    +      n, transactionTimeout, this)
    +    transactionExecutorOpt.map(executor => {
    +      executor.submit(processor)
    +    })
    +    // Wait until a batch is available - can be null if some error was thrown
    +    processor.getEventBatch match {
    +      case ErrorEventBatch => throw new FlumeException("Something went wrong. No events" +
    +        " retrieved from channel.")
    +      case eventBatch: EventBatch =>
    +        processorMap.put(sequenceNumber, processor)
    +        if (LOG.isDebugEnabled()) {
    +          LOG.debug("Sent " + eventBatch.getEvents.size() +
    +            " events with sequence number: " + eventBatch.getSequenceNumber)
    +        }
    +        eventBatch
    +    }
    +  }
    +
    +  /**
    +   * Called by Spark to indicate successful commit of a batch
    +   * @param sequenceNumber The sequence number of the event batch that was successful
    +   */
    +  override def ack(sequenceNumber: CharSequence): Void = {
    +    completeTransaction(sequenceNumber, success = true)
    +    null
    +  }
    +
    +  /**
    +   * Called by Spark to indicate failed commit of a batch
    +   * @param sequenceNumber The sequence number of the event batch that failed
    +   * @return
    +   */
    +  override def nack(sequenceNumber: CharSequence): Void = {
    +    completeTransaction(sequenceNumber, success = false)
    +    LOG.info("Spark failed to commit transaction. Will reattempt events.")
    +    null
    +  }
    +
    +  /**
    +   * Helper method to commit or rollback a transaction.
    +   * @param sequenceNumber The sequence number of the batch that was completed
    +   * @param success Whether the batch was successful or not.
    +   */
    +  private def completeTransaction(sequenceNumber: CharSequence, success: Boolean) {
    +    Option(removeAndGetProcessor(sequenceNumber)).map(processor => {
    +      processor.batchProcessed(success)
    +    })
    +  }
    +
    +  /**
    +   * Helper method to remove the TxnProcessor for a Sequence Number. Can be used to avoid a leak.
    +   * @param sequenceNumber
    +   * @return The transaction processor for the corresponding batch. Note that this instance is no
    +   *         longer tracked and the caller is responsible for that txn processor.
    +   */
    +  private[flume] def removeAndGetProcessor(sequenceNumber: CharSequence): TransactionProcessor = {
    +    processorMap.remove(sequenceNumber.toString) // The toString is required!
    +  }
    +
    +  /**
    +   * Shuts down the executor used to process transactions.
    +   */
    +  def shutdown() {
    +    transactionExecutorOpt.map(executor => {
    +      executor.shutdownNow()
    +    })
    +  }
    +}
    +
    +/**
    + * Object representing an empty batch returned by the txn processor due to some error.
    + */
    +case object ErrorEventBatch extends EventBatch
    +
    +// Flume forces transactions to be thread-local (horrible, I know!)
    +// So the sink basically spawns a new thread to pull the events out within a transaction.
    +// The thread fills in the event batch object that is set before the thread is scheduled.
    +// After filling it in, the thread waits on a condition - which is released only
    +// when the success message comes back for the specific sequence number for that event batch.
    +/**
    + * This class represents a transaction on the Flume channel. This class runs a separate thread
    + * which owns the transaction. The thread is blocked until the success call for that transaction
    + * comes back with an ACK or NACK.
    + * @param channel The channel from which to pull events
    + * @param seqNum The sequence number to use for the transaction. Must be unique
    + * @param maxBatchSize The maximum number of events to process per batch
    + * @param transactionTimeout Time in seconds after which a transaction must be rolled back
    + *                           without waiting for an ACK from Spark
    + * @param parent The parent [[SparkAvroCallbackHandler]] instance, for reporting timeouts
    + */
    +private class TransactionProcessor(val channel: Channel, val seqNum: String,
    +  var maxBatchSize: Int, val transactionTimeout: Int,
    +  val parent: SparkAvroCallbackHandler) extends Callable[Void] {
    +
    +  private val LOG = LoggerFactory.getLogger(classOf[TransactionProcessor])
    +
    +  // If a real batch is not returned, we always have to return an error batch.
    +  @volatile private var eventBatch: EventBatch = ErrorEventBatch
    +
    +  // Synchronization primitives
    +  val batchGeneratedLatch = new CountDownLatch(1)
    +  val batchAckLatch = new CountDownLatch(1)
    +
    +  // Sanity check to ensure we don't loop like crazy
    +  val totalAttemptsToRemoveFromChannel = Int.MaxValue / 2
    +
    +  // OK to use volatile, since the change would only make this true (otherwise it will be
    +  // changed to false - we never apply a negation operation to this) - which means the transaction
    +  // succeeded.
    +  @volatile private var batchSuccess = false
    +
    +  // The transaction that this processor would handle
    +  var txOpt: Option[Transaction] = None
    +
    +  /**
    +   * Get an event batch from the channel. This method will block until a batch of events is
    +   * available from the channel. If no events are available after a large number of attempts of
    +   * polling the channel, this method will return [[ErrorEventBatch]].
    +   *
    +   * @return An [[EventBatch]] instance with sequence number set to [[seqNum]], filled with a
    +   *         maximum of [[maxBatchSize]] events
    +   */
    +  def getEventBatch: EventBatch = {
    +    batchGeneratedLatch.await()
    +    eventBatch
    +  }
    +
    +  /**
    +   * This method is to be called by the sink when it receives an ACK or NACK from Spark. This
    +   * method is a no-op if it is called after [[transactionTimeout]] has expired since
    +   * [[getEventBatch]] returned a batch of events.
    +   * @param success True if an ACK was received and the transaction should be committed, else false.
    +   */
    +  def batchProcessed(success: Boolean) {
    +    if (LOG.isDebugEnabled) {
    +      LOG.debug("Batch processed for sequence number: " + seqNum)
    +    }
    +    batchSuccess = success
    +    batchAckLatch.countDown()
    +  }
    +
    +  /**
    +   * Populates events into the event batch. If the batch cannot be populated,
    +   * this method will not set the event batch which will stay [[ErrorEventBatch]]
    +   */
    +  private def populateEvents() {
    +    try {
    +      txOpt = Option(channel.getTransaction)
    +      txOpt.map(tx => {
    +        tx.begin()
    +        val events = new util.ArrayList[SparkSinkEvent](maxBatchSize)
    +        val loop = new Breaks
    +        var gotEventsInThisTxn = false
    +        var loopCounter: Int = 0
    +        loop.breakable {
    +          while (events.size() < maxBatchSize
    +            && loopCounter < totalAttemptsToRemoveFromChannel) {
    +            loopCounter += 1
    +            Option(channel.take()) match {
    +              case Some(event) =>
    +                events.add(new SparkSinkEvent(toCharSequenceMap(event.getHeaders),
    +                  ByteBuffer.wrap(event.getBody)))
    +                gotEventsInThisTxn = true
    +              case None =>
    +                if (!gotEventsInThisTxn) {
    +                  TimeUnit.MILLISECONDS.sleep(500)
    +                } else {
    +                  loop.break()
    +                }
    +            }
    +          }
    +        }
    +        if (!gotEventsInThisTxn) {
    +          throw new FlumeException("Tried too many times, didn't get any events from the channel")
    +        }
    +        // At this point, the events are available, so fill them into the event batch
    +        eventBatch = new EventBatch(seqNum, events)
    +      })
    +    } catch {
    +      case e: Throwable =>
    +        LOG.error("Error while processing transaction.", e)
    +        try {
    +          txOpt.map(tx => {
    +            rollbackAndClose(tx, close = true)
    +          })
    +        } finally {
    +          // Avro might serialize the exception and cause a NACK,
    +          // so don't bother with the transaction
    +          txOpt = None
    +        }
    +    } finally {
    +      batchGeneratedLatch.countDown()
    +    }
    +  }
    +
    +  /**
    +   * Waits for upto [[transactionTimeout]] seconds for an ACK. If an ACK comes in,
    +   * this method commits the transaction with the channel. If the ACK does not come in within
    +   * that time or a NACK comes in, this method rolls back the transaction.
    +   */
    +  private def processAckOrNack() {
    +    batchAckLatch.await(transactionTimeout, TimeUnit.SECONDS)
    +    txOpt.map(tx => {
    +      if (batchSuccess) {
    +        try {
    +          tx.commit()
    +        } catch {
    +          case e: Throwable =>
    +            rollbackAndClose(tx, close = false) // tx will be closed later anyway
    +        } finally {
    +          tx.close()
    --- End diff --
    
    Close is technically idempotent, though I am not sure Flume actually guarantees that (the interface does not specify this) - which is why the additional parameter.


---
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 infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] spark pull request: SPARK-1729. Make Flume pull data from source, ...

Posted by harishreedharan <gi...@git.apache.org>.
Github user harishreedharan commented on a diff in the pull request:

    https://github.com/apache/spark/pull/807#discussion_r13466244
  
    --- Diff: external/flume-sink/src/main/avro/sparkflume.avdl ---
    @@ -0,0 +1,40 @@
    +/**
    + * 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.
    + */
    +
    +@namespace("org.apache.spark.flume")
    +
    +protocol SparkFlumeProtocol {
    +
    +  record SparkSinkEvent {
    +    map<string> headers;
    +    bytes body;
    +  }
    +
    +  record EventBatch {
    +    string sequenceNumber;
    +    array<SparkSinkEvent> eventBatch;
    --- End diff --
    
    Will do :-)


---
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 infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] spark pull request: [STREAMING] SPARK-1729. Make Flume pull data f...

Posted by tdas <gi...@git.apache.org>.
Github user tdas commented on the pull request:

    https://github.com/apache/spark/pull/807#issuecomment-50378082
  
    Jenkins, test this please.


---
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 infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] spark pull request: [STREAMING] SPARK-1729. Make Flume pull data f...

Posted by SparkQA <gi...@git.apache.org>.
Github user SparkQA commented on the pull request:

    https://github.com/apache/spark/pull/807#issuecomment-50394230
  
    QA tests have started for PR 807. This patch merges cleanly. <br>View progress: https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/17303/consoleFull


---
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 infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] spark pull request: SPARK-1729. Make Flume pull data from source, ...

Posted by harishreedharan <gi...@git.apache.org>.
Github user harishreedharan commented on a diff in the pull request:

    https://github.com/apache/spark/pull/807#discussion_r13835151
  
    --- Diff: external/flume-sink/src/main/scala/org/apache/spark/flume/sink/SparkSink.scala ---
    @@ -0,0 +1,432 @@
    +/*
    + * 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.flume.sink
    +
    +import java.net.InetSocketAddress
    +import java.nio.ByteBuffer
    +import java.util
    +import java.util.concurrent._
    +import java.util.concurrent.atomic.AtomicLong
    +
    +import scala.util.control.Breaks
    +
    +import com.google.common.util.concurrent.ThreadFactoryBuilder
    +import org.apache.avro.ipc.NettyServer
    +import org.apache.avro.ipc.specific.SpecificResponder
    +import org.apache.commons.lang.RandomStringUtils
    +import org.apache.flume.Sink.Status
    +import org.apache.flume.conf.{ConfigurationException, Configurable}
    +import org.apache.flume.sink.AbstractSink
    +import org.apache.flume.{Channel, Transaction, FlumeException, Context}
    +import org.slf4j.LoggerFactory
    +
    +import org.apache.spark.flume.{SparkSinkEvent, EventBatch, SparkFlumeProtocol}
    +
    +/**
    + * A sink that uses Avro RPC to run a server that can be polled by Spark's
    + * FlumePollingInputDStream. This sink has the following configuration parameters:
    + *
    + * hostname - The hostname to bind to. Default: 0.0.0.0
    + * port - The port to bind to. (No default - mandatory)
    + * timeout - Time in seconds after which a transaction is rolled back,
    + * if an ACK is not received from Spark within that time
    + * threads - Number of threads to use to receive requests from Spark (Default: 10)
    + *
    + */
    +// Flume forces transactions to be thread-local. So each transaction *must* be committed, or
    +// rolled back from the thread it was originally created in. So each getEvents call from Spark
    +// creates a TransactionProcessor which runs in a new thread, in which the transaction is created
    +// and events are pulled off the channel. Once the events are sent to spark,
    +// that thread is blocked and the TransactionProcessor is saved in a map,
    +// until an ACK or NACK comes back or the transaction times out (after the specified timeout).
    +// When the response comes, the TransactionProcessor is retrieved and then unblocked,
    +// at which point the transaction is committed or rolled back.
    +class SparkSink extends AbstractSink with Configurable {
    +
    +  // Size of the pool to use for holding transaction processors.
    +  private var poolSize: Integer = SparkSinkConfig.DEFAULT_THREADS
    +
    +  // Timeout for each transaction. If spark does not respond in this much time,
    +  // rollback the transaction
    +  private var transactionTimeout = SparkSinkConfig.DEFAULT_TRANSACTION_TIMEOUT
    +
    +  // Address info to bind on
    +  private var hostname: String = SparkSinkConfig.DEFAULT_HOSTNAME
    +  private var port: Int = 0
    +
    +  // Handle to the server
    +  private var serverOpt: Option[NettyServer] = None
    +
    +  // The handler that handles the callback from Avro
    +  private var handler: Option[SparkAvroCallbackHandler] = None
    +
    +  // Latch that blocks off the Flume framework from wasting 1 thread.
    +  private val blockingLatch = new CountDownLatch(1)
    +
    +  override def start() {
    +    handler = Option(new SparkAvroCallbackHandler(poolSize, getChannel, transactionTimeout))
    +    val responder = new SpecificResponder(classOf[SparkFlumeProtocol], handler.get)
    +    // Using the constructor that takes specific thread-pools requires bringing in netty
    +    // dependencies which are being excluded in the build. In practice,
    +    // Netty dependencies are already available on the JVM as Flume would have pulled them in.
    +    serverOpt = Option(new NettyServer(responder, new InetSocketAddress(hostname, port)))
    +    serverOpt.map(server => {
    +      server.start()
    +    })
    +    super.start()
    +  }
    +
    +  override def stop() {
    +    handler.map(callbackHandler => {
    +      callbackHandler.shutdown()
    +    })
    +    serverOpt.map(server => {
    +      server.close()
    +      server.join()
    +    })
    +    blockingLatch.countDown()
    +    super.stop()
    +  }
    +
    +  /**
    +   * @param ctx
    +   */
    +  override def configure(ctx: Context) {
    +    import SparkSinkConfig._
    +    hostname = ctx.getString(CONF_HOSTNAME, DEFAULT_HOSTNAME)
    +    port = Option(ctx.getInteger(CONF_PORT)).
    +      getOrElse(throw new ConfigurationException("The port to bind to must be specified"))
    +    poolSize = ctx.getInteger(THREADS, DEFAULT_THREADS)
    +    transactionTimeout = ctx.getInteger(CONF_TRANSACTION_TIMEOUT, DEFAULT_TRANSACTION_TIMEOUT)
    +  }
    +
    +  override def process(): Status = {
    +    // This method is called in a loop by the Flume framework - block it until the sink is
    +    // stopped to save CPU resources. The sink runner will interrupt this thread when the sink is
    +    // being shut down.
    +    blockingLatch.await()
    +    Status.BACKOFF
    +  }
    +}
    +
    +/**
    + * Class that implements the SparkFlumeProtocol, that is used by the Avro Netty Server to process
    + * requests. Each getEvents, ack and nack call is forwarded to an instance of this class.
    + * @param threads Number of threads to use to process requests.
    + * @param channel The channel that the sink pulls events from
    + * @param transactionTimeout Timeout in millis after which the transaction if not acked by Spark
    + *                           is rolled back.
    + */
    +private class SparkAvroCallbackHandler(val threads: Int, val channel: Channel,
    +  val transactionTimeout: Int) extends SparkFlumeProtocol {
    +  private val LOG = LoggerFactory.getLogger(classOf[SparkAvroCallbackHandler])
    +  val transactionExecutorOpt = Option(Executors.newFixedThreadPool(threads,
    +    new ThreadFactoryBuilder().setDaemon(true)
    +      .setNameFormat("Spark Sink Processor Thread - %d").build()))
    +  private val processorMap = new ConcurrentHashMap[CharSequence, TransactionProcessor]()
    +  // This sink will not persist sequence numbers and reuses them if it gets restarted.
    +  // So it is possible to commit a transaction which may have been meant for the sink before the
    +  // restart.
    +  // Since the new txn may not have the same sequence number we must guard against accidentally
    +  // committing a new transaction. To reduce the probability of that happening a random string is
    +  // prepended to the sequence number. Does not change for life of sink
    +  private val seqBase = RandomStringUtils.randomAlphanumeric(8)
    +  private val seqCounter = new AtomicLong(0)
    +
    +  /**
    +   * Returns a bunch of events to Spark over Avro RPC.
    +   * @param n Maximum number of events to return in a batch
    +   * @return [[EventBatch]] instance that has a sequence number and an array of at most n events
    +   */
    +  override def getEventBatch(n: Int): EventBatch = {
    +    val sequenceNumber = seqBase + seqCounter.incrementAndGet()
    +    val processor = new TransactionProcessor(channel, sequenceNumber,
    +      n, transactionTimeout, this)
    +    transactionExecutorOpt.map(executor => {
    +      executor.submit(processor)
    +    })
    +    // Wait until a batch is available - can be null if some error was thrown
    +    processor.getEventBatch match {
    +      case ErrorEventBatch => throw new FlumeException("Something went wrong. No events" +
    +        " retrieved from channel.")
    +      case eventBatch: EventBatch =>
    +        processorMap.put(sequenceNumber, processor)
    +        if (LOG.isDebugEnabled()) {
    +          LOG.debug("Sent " + eventBatch.getEvents.size() +
    +            " events with sequence number: " + eventBatch.getSequenceNumber)
    +        }
    +        eventBatch
    +    }
    +  }
    +
    +  /**
    +   * Called by Spark to indicate successful commit of a batch
    +   * @param sequenceNumber The sequence number of the event batch that was successful
    +   */
    +  override def ack(sequenceNumber: CharSequence): Void = {
    +    completeTransaction(sequenceNumber, success = true)
    +    null
    +  }
    +
    +  /**
    +   * Called by Spark to indicate failed commit of a batch
    +   * @param sequenceNumber The sequence number of the event batch that failed
    +   * @return
    +   */
    +  override def nack(sequenceNumber: CharSequence): Void = {
    +    completeTransaction(sequenceNumber, success = false)
    +    LOG.info("Spark failed to commit transaction. Will reattempt events.")
    +    null
    +  }
    +
    +  /**
    +   * Helper method to commit or rollback a transaction.
    +   * @param sequenceNumber The sequence number of the batch that was completed
    +   * @param success Whether the batch was successful or not.
    +   */
    +  private def completeTransaction(sequenceNumber: CharSequence, success: Boolean) {
    +    Option(removeAndGetProcessor(sequenceNumber)).map(processor => {
    +      processor.batchProcessed(success)
    +    })
    +  }
    +
    +  /**
    +   * Helper method to remove the TxnProcessor for a Sequence Number. Can be used to avoid a leak.
    +   * @param sequenceNumber
    +   * @return The transaction processor for the corresponding batch. Note that this instance is no
    +   *         longer tracked and the caller is responsible for that txn processor.
    +   */
    +  private[flume] def removeAndGetProcessor(sequenceNumber: CharSequence): TransactionProcessor = {
    +    processorMap.remove(sequenceNumber.toString) // The toString is required!
    +  }
    +
    +  /**
    +   * Shuts down the executor used to process transactions.
    +   */
    +  def shutdown() {
    +    transactionExecutorOpt.map(executor => {
    +      executor.shutdownNow()
    +    })
    +  }
    +}
    +
    +/**
    + * Object representing an empty batch returned by the txn processor due to some error.
    + */
    +case object ErrorEventBatch extends EventBatch
    +
    +// Flume forces transactions to be thread-local (horrible, I know!)
    +// So the sink basically spawns a new thread to pull the events out within a transaction.
    +// The thread fills in the event batch object that is set before the thread is scheduled.
    +// After filling it in, the thread waits on a condition - which is released only
    +// when the success message comes back for the specific sequence number for that event batch.
    +/**
    + * This class represents a transaction on the Flume channel. This class runs a separate thread
    + * which owns the transaction. The thread is blocked until the success call for that transaction
    + * comes back with an ACK or NACK.
    + * @param channel The channel from which to pull events
    + * @param seqNum The sequence number to use for the transaction. Must be unique
    + * @param maxBatchSize The maximum number of events to process per batch
    + * @param transactionTimeout Time in seconds after which a transaction must be rolled back
    + *                           without waiting for an ACK from Spark
    + * @param parent The parent [[SparkAvroCallbackHandler]] instance, for reporting timeouts
    + */
    +private class TransactionProcessor(val channel: Channel, val seqNum: String,
    +  var maxBatchSize: Int, val transactionTimeout: Int,
    +  val parent: SparkAvroCallbackHandler) extends Callable[Void] {
    +
    +  private val LOG = LoggerFactory.getLogger(classOf[TransactionProcessor])
    +
    +  // If a real batch is not returned, we always have to return an error batch.
    +  @volatile private var eventBatch: EventBatch = ErrorEventBatch
    +
    +  // Synchronization primitives
    +  val batchGeneratedLatch = new CountDownLatch(1)
    +  val batchAckLatch = new CountDownLatch(1)
    +
    +  // Sanity check to ensure we don't loop like crazy
    +  val totalAttemptsToRemoveFromChannel = Int.MaxValue / 2
    +
    +  // OK to use volatile, since the change would only make this true (otherwise it will be
    +  // changed to false - we never apply a negation operation to this) - which means the transaction
    +  // succeeded.
    +  @volatile private var batchSuccess = false
    +
    +  // The transaction that this processor would handle
    +  var txOpt: Option[Transaction] = None
    +
    +  /**
    +   * Get an event batch from the channel. This method will block until a batch of events is
    +   * available from the channel. If no events are available after a large number of attempts of
    +   * polling the channel, this method will return [[ErrorEventBatch]].
    +   *
    +   * @return An [[EventBatch]] instance with sequence number set to [[seqNum]], filled with a
    +   *         maximum of [[maxBatchSize]] events
    +   */
    +  def getEventBatch: EventBatch = {
    +    batchGeneratedLatch.await()
    +    eventBatch
    +  }
    +
    +  /**
    +   * This method is to be called by the sink when it receives an ACK or NACK from Spark. This
    +   * method is a no-op if it is called after [[transactionTimeout]] has expired since
    +   * [[getEventBatch]] returned a batch of events.
    +   * @param success True if an ACK was received and the transaction should be committed, else false.
    +   */
    +  def batchProcessed(success: Boolean) {
    +    if (LOG.isDebugEnabled) {
    +      LOG.debug("Batch processed for sequence number: " + seqNum)
    +    }
    +    batchSuccess = success
    +    batchAckLatch.countDown()
    +  }
    +
    +  /**
    +   * Populates events into the event batch. If the batch cannot be populated,
    +   * this method will not set the event batch which will stay [[ErrorEventBatch]]
    +   */
    +  private def populateEvents() {
    +    try {
    +      txOpt = Option(channel.getTransaction)
    --- End diff --
    
    Actually if the transaction returns null, eventBatch will remain ErrorEventBatch or None - if that change is made (from the initial assignment) which leads to a FlumeException - which will be caught by Avro IPC and a corresponding exception thrown on the other side(streaming side), which we catch and log.(Avro IPC guarantees this) 


---
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 infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] spark pull request: SPARK-1729. Make Flume pull data from source, ...

Posted by harishreedharan <gi...@git.apache.org>.
Github user harishreedharan commented on a diff in the pull request:

    https://github.com/apache/spark/pull/807#discussion_r13466211
  
    --- Diff: external/flume-sink/src/main/scala/org/apache/spark/flume/sink/SparkSink.scala ---
    @@ -0,0 +1,392 @@
    +/*
    + * 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.flume.sink
    +
    +import org.apache.flume.sink.AbstractSink
    +import java.util.concurrent.locks.ReentrantLock
    +import org.apache.flume.Sink.Status
    +import org.apache.spark.flume.{SparkSinkEvent, EventBatch, SparkFlumeProtocol}
    +import scala.util.control.Breaks
    +import java.nio.ByteBuffer
    +import org.apache.flume.{FlumeException, Context}
    +import org.slf4j.LoggerFactory
    +import java.util.concurrent.atomic.AtomicLong
    +import org.apache.commons.lang.RandomStringUtils
    +import java.util.concurrent._
    +import java.util
    +import org.apache.flume.conf.{ConfigurationException, Configurable}
    +import com.google.common.util.concurrent.ThreadFactoryBuilder
    +import org.apache.avro.ipc.NettyServer
    +import org.apache.avro.ipc.specific.SpecificResponder
    +import java.net.InetSocketAddress
    +
    +class SparkSink() extends AbstractSink with Configurable {
    +  private val LOG = LoggerFactory.getLogger(this.getClass)
    +  private val lock = new ReentrantLock()
    +  private val blockingCondition = lock.newCondition()
    +
    +  // This sink will not persist sequence numbers and reuses them if it gets restarted.
    +  // So it is possible to commit a transaction which may have been meant for the sink before the
    +  // restart.
    +  // Since the new txn may not have the same sequence number we must guard against accidentally
    +  // committing
    +  // a new transaction. To reduce the probability of that happening a random string is prepended
    +  // to the sequence number.
    +  // Does not change for life of sink
    +  private val seqBase = RandomStringUtils.randomAlphanumeric(8)
    +  // Incremented for each transaction
    +  private val seqNum = new AtomicLong(0)
    +
    +  private var transactionExecutorOpt: Option[ExecutorService] = None
    +
    +  private var numProcessors: Integer = SparkSinkConfig.DEFAULT_PROCESSOR_COUNT
    +  private var transactionTimeout = SparkSinkConfig.DEFAULT_TRANSACTION_TIMEOUT
    +
    +  private val processorMap = new ConcurrentHashMap[CharSequence, TransactionProcessor]()
    +
    +  private var processorFactory: Option[SparkHandlerFactory] = None
    +  private var hostname: String = SparkSinkConfig.DEFAULT_HOSTNAME
    +  private var port: Int = 0
    +  private var maxThreads: Int = SparkSinkConfig.DEFAULT_MAX_THREADS
    +  private var serverOpt: Option[NettyServer] = None
    +  private var running = false
    +
    +  override def start() {
    +    transactionExecutorOpt = Option(Executors.newFixedThreadPool(numProcessors,
    +      new ThreadFactoryBuilder().setDaemon(true)
    +        .setNameFormat("Spark Sink, " + getName + " Processor Thread - %d").build()))
    +
    +    processorFactory = Option(new SparkHandlerFactory(numProcessors))
    +
    +    val responder = new SpecificResponder(classOf[SparkFlumeProtocol], new AvroCallbackHandler())
    +
    +    // Using the constructor that takes specific thread-pools requires bringing in netty
    +    // dependencies which are being excluded in the build. In practice,
    +    // Netty dependencies are already available on the JVM as Flume would have pulled them in.
    +    serverOpt = Option(new NettyServer(responder, new InetSocketAddress(hostname, port)))
    +
    +    serverOpt.map(server => server.start())
    +    lock.lock()
    +    try {
    +      running = true
    +    } finally {
    +      lock.unlock()
    +    }
    +    super.start()
    +  }
    +
    +  override def stop() {
    +    transactionExecutorOpt.map(executor => executor.shutdownNow())
    +    serverOpt.map(server => {
    +      server.close()
    +      server.join()
    +    })
    +    lock.lock()
    +    try {
    +      running = false
    +      blockingCondition.signalAll()
    +    } finally {
    +      lock.unlock()
    +    }
    +  }
    +
    +  override def configure(ctx: Context) {
    +    import SparkSinkConfig._
    +    hostname = ctx.getString(CONF_HOSTNAME, DEFAULT_HOSTNAME)
    +    val portOpt = Option(ctx.getInteger(CONF_PORT))
    +    if(portOpt.isDefined) {
    +      port = portOpt.get
    +    } else {
    +      throw new ConfigurationException("The Port to bind must be specified")
    +    }
    +    numProcessors = ctx.getInteger(PROCESSOR_COUNT, DEFAULT_PROCESSOR_COUNT)
    +    transactionTimeout = ctx.getInteger(CONF_TRANSACTION_TIMEOUT, DEFAULT_TRANSACTION_TIMEOUT)
    +    maxThreads = ctx.getInteger(CONF_MAX_THREADS, DEFAULT_MAX_THREADS)
    +  }
    +
    +  override def process(): Status = {
    +    // This method is called in a loop by the Flume framework - block it until the sink is
    +    // stopped to save CPU resources
    +    lock.lock()
    +    try {
    +      while(running) {
    +        blockingCondition.await()
    +      }
    +    } finally {
    +      lock.unlock()
    +    }
    +    Status.BACKOFF
    +  }
    +
    +
    +  // Object representing an empty batch returned by the txn processor due to some error.
    +  case object ErrorEventBatch extends EventBatch
    +
    +  private class AvroCallbackHandler() extends SparkFlumeProtocol {
    +
    +    override def getEventBatch(n: Int): EventBatch = {
    +      val processor = processorFactory.get.checkOut(n)
    +      transactionExecutorOpt.map(executor => executor.submit(processor))
    +      // Wait until a batch is available - can be null if some error was thrown
    +      val eventBatch = processor.eventQueue.take()
    +      eventBatch match {
    +        case ErrorEventBatch => throw new FlumeException("Something went wrong. No events" +
    +          " retrieved from channel.")
    +        case events => {
    +          processorMap.put(events.getSequenceNumber, processor)
    +          if (LOG.isDebugEnabled) {
    +            LOG.debug("Sent " + events.getEventBatch.size() +
    +              " events with sequence number: " + events.getSequenceNumber)
    +          }
    +          events
    +        }
    +      }
    +    }
    +
    +    override def ack(sequenceNumber: CharSequence): Void = {
    +      completeTransaction(sequenceNumber, success = true)
    +      null
    +    }
    +
    +    override def nack(sequenceNumber: CharSequence): Void = {
    +      completeTransaction(sequenceNumber, success = false)
    +      LOG.info("Spark failed to commit transaction. Will reattempt events.")
    +      null
    +    }
    +
    +    def completeTransaction(sequenceNumber: CharSequence, success: Boolean) {
    +      val processorOpt = Option(processorMap.remove(sequenceNumber))
    +      if (processorOpt.isDefined) {
    +        val processor = processorOpt.get
    +        processor.resultQueueUpdateLock.lock()
    +        try {
    +          // Is the sequence number the same as the one the processor is processing? If not,
    +          // don't update {
    +          if (processor.eventBatch.getSequenceNumber.equals(sequenceNumber)) {
    +            processor.resultQueue.put(success)
    +          }
    +        } finally {
    +          processor.resultQueueUpdateLock.unlock()
    +        }
    +      }
    +    }
    +  }
    +
    +  // Flume forces transactions to be thread-local (horrible, I know!)
    +  // So the sink basically spawns a new thread to pull the events out within a transaction.
    +  // The thread fills in the event batch object that is set before the thread is scheduled.
    +  // After filling it in, the thread waits on a condition - which is released only
    +  // when the success message comes back for the specific sequence number for that event batch.
    +  /**
    +   * This class represents a transaction on the Flume channel. This class runs a separate thread
    +   * which owns the transaction. It is blocked until the success call for that transaction comes
    +   * back.
    +   * @param maxBatchSize
    +   */
    +  private class TransactionProcessor(var maxBatchSize: Int) extends Callable[Void] {
    +    // Must be set to a new event batch before scheduling this!!
    +    val eventBatch = new EventBatch("", new util.LinkedList[SparkSinkEvent])
    +    val eventQueue = new SynchronousQueue[EventBatch]()
    +    val resultQueue = new SynchronousQueue[Boolean]()
    +    val resultQueueUpdateLock = new ReentrantLock()
    +
    +    object Zero {
    +      val zero = "0" // Oh, I miss static finals
    +    }
    +
    +
    +    override def call(): Void = {
    +      val tx = getChannel.getTransaction
    +      tx.begin()
    +      try {
    +        eventBatch.setSequenceNumber(seqBase + seqNum.incrementAndGet())
    +        val events = eventBatch.getEventBatch
    +        events.clear()
    +        val loop = new Breaks
    +        var gotEventsInThisTxn = false
    +        loop.breakable {
    +          var i = 0
    +          // Using for here causes the maxBatchSize change to be ineffective as the Range gets
    +          // pregenerated
    +          while (i < maxBatchSize) {
    +            i += 1
    +            val eventOpt = Option(getChannel.take())
    +            eventOpt.map(event => {
    +              events.add(new SparkSinkEvent(toCharSequenceMap(event
    +                .getHeaders),
    +                ByteBuffer.wrap(event.getBody)))
    +              gotEventsInThisTxn = true
    +            })
    +            if (eventOpt.isEmpty) {
    +              if (!gotEventsInThisTxn) {
    +                // To avoid sending empty batches, we wait till events are available backing off
    +                // between attempts to get events. Each attempt to get an event though causes one
    +                // iteration to be lost. To ensure that we still send back maxBatchSize number of
    +                // events, we cheat and increase the maxBatchSize by 1 to account for the lost
    +                // iteration. Even throwing an exception is expensive as Avro will serialize it
    +                // and send it over the wire, which is useless. Before incrementing though,
    +                // ensure that we are not anywhere near INT_MAX.
    +                if (maxBatchSize >= Int.MaxValue / 2) {
    +                  // Random sanity check
    +                  throw new RuntimeException("Safety exception - polled too many times, no events!")
    +                }
    +                maxBatchSize += 1
    +                Thread.sleep(500)
    +              } else {
    +                loop.break()
    +              }
    +            }
    +          }
    +        }
    +        // Make the data available to the sender thread
    +        eventQueue.put(eventBatch)
    +
    +        // Wait till timeout for the ack/nack
    +        val maybeResult = Option(resultQueue.poll(transactionTimeout, TimeUnit.SECONDS))
    +        // There is a race condition here.
    +        // 1. This times out.
    +        // 2. The result is empty, so timeout exception is thrown.
    +        // 3. The ack comes in before the finally block is entered
    +        // 4. The thread with the ack has a handle to this processor,
    +        // and another thread has the same processor checked out
    +        // (since the finally block was executed and the processor checked back in)
    +        // 5. The thread with the ack now updates the result queue,
    +        // so the processor thinks it is the ack for the current batch.
    +        // To avoid this - update the sequence number to "0" (with or without a result - does not
    +        // matter).
    +        // In the ack method, check if the seq number is the same as the processor's -
    +        // if they are then update the result queue. Now if the
    +        // processor updates the seq number first - the ack/nack never updates the result. If the
    +        // ack/nack updates the
    +        // result after the timeout but before the seq number is updated to "0" it does not
    +        // matter - the processor would
    +        // still timeout and the result is cleared before reusing the processor.
    +        // Unfortunately, this needs to be done from within a lock
    +        // to make sure that the new sequence number is actually visible to the ack thread
    +        // (happens-before)
    +        resultQueueUpdateLock.lock()
    +        try {
    +          eventBatch.setSequenceNumber(Zero.zero)
    +        } finally {
    +          resultQueueUpdateLock.unlock()
    +        }
    +        eventBatch.getEventBatch.clear()
    +        // If the batch failed on spark side, throw a FlumeException
    +        maybeResult.map(success =>
    +          if (!success) {
    +            throw new
    +                FlumeException("Spark could not accept events. The transaction will be retried.")
    +          }
    +        )
    +        // If the operation timed out, throw a TimeoutException
    +        if (maybeResult.isEmpty) {
    +          throw new TimeoutException("Spark did not respond within the timeout period of " +
    +            transactionTimeout + "seconds. Transaction will be retried")
    +        }
    +        null
    +      } catch {
    +        case e: Throwable =>
    +          try {
    +            LOG.warn("Error while attempting to remove events from the channel.", e)
    +            tx.rollback()
    +          } catch {
    +            case e1: Throwable => LOG.error(
    +              "Rollback failed while attempting to rollback due to commit failure.", e1)
    +          }
    +          null // No point rethrowing the exception
    +      } finally {
    +        // Must *always* release the caller thread
    +        eventQueue.put(ErrorEventBatch)
    +        // In the case of success coming after the timeout, but before resetting the seq number
    +        // remove the event from the map and then clear the value
    +        resultQueue.clear()
    +        processorMap.remove(eventBatch.getSequenceNumber)
    +        processorFactory.get.checkIn(this)
    +        tx.close()
    +      }
    +    }
    +
    +    def toCharSequenceMap(inMap: java.util.Map[String, String]): java.util.Map[CharSequence,
    +      CharSequence] = {
    +      val charSeqMap = new util.HashMap[CharSequence, CharSequence](inMap.size())
    +      charSeqMap.putAll(inMap)
    +      charSeqMap
    +    }
    +  }
    +
    +  private class SparkHandlerFactory(val maxInstances: Int) {
    +    val queue = new scala.collection.mutable.Queue[TransactionProcessor]
    +    val queueModificationLock = new ReentrantLock()
    +    var currentSize = 0
    +    val waitForCheckIn = queueModificationLock.newCondition()
    +
    +    def checkOut(n: Int): TransactionProcessor = {
    +      def getProcessor = {
    +        val processor = queue.dequeue()
    +        processor.maxBatchSize = n
    +        processor
    +      }
    +      queueModificationLock.lock()
    +      try {
    +        if (queue.size > 0) {
    +          getProcessor
    +        }
    +        else {
    +          if (currentSize < maxInstances) {
    +            currentSize += 1
    +            new TransactionProcessor(n)
    +          } else {
    +            // No events in queue and cannot initialize more!
    +            // Since currentSize never reduces, queue size increasing is the only hope
    +            while (queue.size == 0 && currentSize >= maxInstances) {
    +              waitForCheckIn.await()
    +            }
    +            getProcessor
    +          }
    +        }
    +      } finally {
    +        queueModificationLock.unlock()
    +      }
    +    }
    +
    +    def checkIn(processor: TransactionProcessor) {
    +      queueModificationLock.lock()
    --- End diff --
    
    The reason I implemented my own queue is to lazily initialize and keep a tab on the maximum number of processors that are created.


---
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 infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] spark pull request: SPARK-1729. Make Flume pull data from source, ...

Posted by harishreedharan <gi...@git.apache.org>.
Github user harishreedharan commented on a diff in the pull request:

    https://github.com/apache/spark/pull/807#discussion_r13466394
  
    --- Diff: external/flume-sink/src/main/scala/org/apache/spark/flume/sink/SparkSink.scala ---
    @@ -0,0 +1,392 @@
    +/*
    + * 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.flume.sink
    +
    +import org.apache.flume.sink.AbstractSink
    +import java.util.concurrent.locks.ReentrantLock
    +import org.apache.flume.Sink.Status
    +import org.apache.spark.flume.{SparkSinkEvent, EventBatch, SparkFlumeProtocol}
    +import scala.util.control.Breaks
    +import java.nio.ByteBuffer
    +import org.apache.flume.{FlumeException, Context}
    +import org.slf4j.LoggerFactory
    +import java.util.concurrent.atomic.AtomicLong
    +import org.apache.commons.lang.RandomStringUtils
    +import java.util.concurrent._
    +import java.util
    +import org.apache.flume.conf.{ConfigurationException, Configurable}
    +import com.google.common.util.concurrent.ThreadFactoryBuilder
    +import org.apache.avro.ipc.NettyServer
    +import org.apache.avro.ipc.specific.SpecificResponder
    +import java.net.InetSocketAddress
    +
    +class SparkSink() extends AbstractSink with Configurable {
    +  private val LOG = LoggerFactory.getLogger(this.getClass)
    +  private val lock = new ReentrantLock()
    +  private val blockingCondition = lock.newCondition()
    +
    +  // This sink will not persist sequence numbers and reuses them if it gets restarted.
    +  // So it is possible to commit a transaction which may have been meant for the sink before the
    +  // restart.
    +  // Since the new txn may not have the same sequence number we must guard against accidentally
    +  // committing
    +  // a new transaction. To reduce the probability of that happening a random string is prepended
    +  // to the sequence number.
    +  // Does not change for life of sink
    +  private val seqBase = RandomStringUtils.randomAlphanumeric(8)
    +  // Incremented for each transaction
    +  private val seqNum = new AtomicLong(0)
    +
    +  private var transactionExecutorOpt: Option[ExecutorService] = None
    +
    +  private var numProcessors: Integer = SparkSinkConfig.DEFAULT_PROCESSOR_COUNT
    +  private var transactionTimeout = SparkSinkConfig.DEFAULT_TRANSACTION_TIMEOUT
    +
    +  private val processorMap = new ConcurrentHashMap[CharSequence, TransactionProcessor]()
    +
    +  private var processorFactory: Option[SparkHandlerFactory] = None
    +  private var hostname: String = SparkSinkConfig.DEFAULT_HOSTNAME
    +  private var port: Int = 0
    +  private var maxThreads: Int = SparkSinkConfig.DEFAULT_MAX_THREADS
    +  private var serverOpt: Option[NettyServer] = None
    +  private var running = false
    +
    +  override def start() {
    +    transactionExecutorOpt = Option(Executors.newFixedThreadPool(numProcessors,
    +      new ThreadFactoryBuilder().setDaemon(true)
    +        .setNameFormat("Spark Sink, " + getName + " Processor Thread - %d").build()))
    +
    +    processorFactory = Option(new SparkHandlerFactory(numProcessors))
    +
    +    val responder = new SpecificResponder(classOf[SparkFlumeProtocol], new AvroCallbackHandler())
    +
    +    // Using the constructor that takes specific thread-pools requires bringing in netty
    +    // dependencies which are being excluded in the build. In practice,
    +    // Netty dependencies are already available on the JVM as Flume would have pulled them in.
    +    serverOpt = Option(new NettyServer(responder, new InetSocketAddress(hostname, port)))
    +
    +    serverOpt.map(server => server.start())
    +    lock.lock()
    +    try {
    +      running = true
    +    } finally {
    +      lock.unlock()
    +    }
    +    super.start()
    +  }
    +
    +  override def stop() {
    +    transactionExecutorOpt.map(executor => executor.shutdownNow())
    +    serverOpt.map(server => {
    +      server.close()
    +      server.join()
    +    })
    +    lock.lock()
    +    try {
    +      running = false
    +      blockingCondition.signalAll()
    +    } finally {
    +      lock.unlock()
    +    }
    +  }
    +
    +  override def configure(ctx: Context) {
    +    import SparkSinkConfig._
    +    hostname = ctx.getString(CONF_HOSTNAME, DEFAULT_HOSTNAME)
    +    val portOpt = Option(ctx.getInteger(CONF_PORT))
    +    if(portOpt.isDefined) {
    +      port = portOpt.get
    +    } else {
    +      throw new ConfigurationException("The Port to bind must be specified")
    +    }
    +    numProcessors = ctx.getInteger(PROCESSOR_COUNT, DEFAULT_PROCESSOR_COUNT)
    +    transactionTimeout = ctx.getInteger(CONF_TRANSACTION_TIMEOUT, DEFAULT_TRANSACTION_TIMEOUT)
    +    maxThreads = ctx.getInteger(CONF_MAX_THREADS, DEFAULT_MAX_THREADS)
    +  }
    +
    +  override def process(): Status = {
    +    // This method is called in a loop by the Flume framework - block it until the sink is
    +    // stopped to save CPU resources
    +    lock.lock()
    +    try {
    +      while(running) {
    +        blockingCondition.await()
    +      }
    +    } finally {
    +      lock.unlock()
    +    }
    +    Status.BACKOFF
    +  }
    +
    +
    +  // Object representing an empty batch returned by the txn processor due to some error.
    +  case object ErrorEventBatch extends EventBatch
    +
    +  private class AvroCallbackHandler() extends SparkFlumeProtocol {
    +
    +    override def getEventBatch(n: Int): EventBatch = {
    +      val processor = processorFactory.get.checkOut(n)
    +      transactionExecutorOpt.map(executor => executor.submit(processor))
    +      // Wait until a batch is available - can be null if some error was thrown
    +      val eventBatch = processor.eventQueue.take()
    +      eventBatch match {
    +        case ErrorEventBatch => throw new FlumeException("Something went wrong. No events" +
    +          " retrieved from channel.")
    +        case events => {
    +          processorMap.put(events.getSequenceNumber, processor)
    +          if (LOG.isDebugEnabled) {
    +            LOG.debug("Sent " + events.getEventBatch.size() +
    +              " events with sequence number: " + events.getSequenceNumber)
    +          }
    +          events
    +        }
    +      }
    +    }
    +
    +    override def ack(sequenceNumber: CharSequence): Void = {
    +      completeTransaction(sequenceNumber, success = true)
    +      null
    +    }
    +
    +    override def nack(sequenceNumber: CharSequence): Void = {
    +      completeTransaction(sequenceNumber, success = false)
    +      LOG.info("Spark failed to commit transaction. Will reattempt events.")
    +      null
    +    }
    +
    +    def completeTransaction(sequenceNumber: CharSequence, success: Boolean) {
    +      val processorOpt = Option(processorMap.remove(sequenceNumber))
    +      if (processorOpt.isDefined) {
    +        val processor = processorOpt.get
    +        processor.resultQueueUpdateLock.lock()
    +        try {
    +          // Is the sequence number the same as the one the processor is processing? If not,
    +          // don't update {
    +          if (processor.eventBatch.getSequenceNumber.equals(sequenceNumber)) {
    +            processor.resultQueue.put(success)
    +          }
    +        } finally {
    +          processor.resultQueueUpdateLock.unlock()
    +        }
    +      }
    +    }
    +  }
    +
    +  // Flume forces transactions to be thread-local (horrible, I know!)
    +  // So the sink basically spawns a new thread to pull the events out within a transaction.
    +  // The thread fills in the event batch object that is set before the thread is scheduled.
    +  // After filling it in, the thread waits on a condition - which is released only
    +  // when the success message comes back for the specific sequence number for that event batch.
    +  /**
    +   * This class represents a transaction on the Flume channel. This class runs a separate thread
    +   * which owns the transaction. It is blocked until the success call for that transaction comes
    +   * back.
    +   * @param maxBatchSize
    +   */
    +  private class TransactionProcessor(var maxBatchSize: Int) extends Callable[Void] {
    +    // Must be set to a new event batch before scheduling this!!
    +    val eventBatch = new EventBatch("", new util.LinkedList[SparkSinkEvent])
    +    val eventQueue = new SynchronousQueue[EventBatch]()
    +    val resultQueue = new SynchronousQueue[Boolean]()
    +    val resultQueueUpdateLock = new ReentrantLock()
    +
    +    object Zero {
    +      val zero = "0" // Oh, I miss static finals
    +    }
    +
    +
    +    override def call(): Void = {
    +      val tx = getChannel.getTransaction
    +      tx.begin()
    +      try {
    +        eventBatch.setSequenceNumber(seqBase + seqNum.incrementAndGet())
    +        val events = eventBatch.getEventBatch
    +        events.clear()
    +        val loop = new Breaks
    +        var gotEventsInThisTxn = false
    +        loop.breakable {
    +          var i = 0
    +          // Using for here causes the maxBatchSize change to be ineffective as the Range gets
    +          // pregenerated
    +          while (i < maxBatchSize) {
    +            i += 1
    +            val eventOpt = Option(getChannel.take())
    +            eventOpt.map(event => {
    +              events.add(new SparkSinkEvent(toCharSequenceMap(event
    +                .getHeaders),
    +                ByteBuffer.wrap(event.getBody)))
    +              gotEventsInThisTxn = true
    +            })
    +            if (eventOpt.isEmpty) {
    +              if (!gotEventsInThisTxn) {
    +                // To avoid sending empty batches, we wait till events are available backing off
    +                // between attempts to get events. Each attempt to get an event though causes one
    +                // iteration to be lost. To ensure that we still send back maxBatchSize number of
    +                // events, we cheat and increase the maxBatchSize by 1 to account for the lost
    +                // iteration. Even throwing an exception is expensive as Avro will serialize it
    +                // and send it over the wire, which is useless. Before incrementing though,
    +                // ensure that we are not anywhere near INT_MAX.
    +                if (maxBatchSize >= Int.MaxValue / 2) {
    +                  // Random sanity check
    +                  throw new RuntimeException("Safety exception - polled too many times, no events!")
    +                }
    +                maxBatchSize += 1
    +                Thread.sleep(500)
    +              } else {
    +                loop.break()
    +              }
    +            }
    +          }
    +        }
    +        // Make the data available to the sender thread
    +        eventQueue.put(eventBatch)
    +
    +        // Wait till timeout for the ack/nack
    +        val maybeResult = Option(resultQueue.poll(transactionTimeout, TimeUnit.SECONDS))
    +        // There is a race condition here.
    +        // 1. This times out.
    +        // 2. The result is empty, so timeout exception is thrown.
    +        // 3. The ack comes in before the finally block is entered
    +        // 4. The thread with the ack has a handle to this processor,
    +        // and another thread has the same processor checked out
    +        // (since the finally block was executed and the processor checked back in)
    +        // 5. The thread with the ack now updates the result queue,
    +        // so the processor thinks it is the ack for the current batch.
    +        // To avoid this - update the sequence number to "0" (with or without a result - does not
    +        // matter).
    +        // In the ack method, check if the seq number is the same as the processor's -
    +        // if they are then update the result queue. Now if the
    +        // processor updates the seq number first - the ack/nack never updates the result. If the
    +        // ack/nack updates the
    +        // result after the timeout but before the seq number is updated to "0" it does not
    +        // matter - the processor would
    +        // still timeout and the result is cleared before reusing the processor.
    +        // Unfortunately, this needs to be done from within a lock
    +        // to make sure that the new sequence number is actually visible to the ack thread
    +        // (happens-before)
    +        resultQueueUpdateLock.lock()
    +        try {
    +          eventBatch.setSequenceNumber(Zero.zero)
    +        } finally {
    +          resultQueueUpdateLock.unlock()
    +        }
    +        eventBatch.getEventBatch.clear()
    +        // If the batch failed on spark side, throw a FlumeException
    +        maybeResult.map(success =>
    +          if (!success) {
    +            throw new
    +                FlumeException("Spark could not accept events. The transaction will be retried.")
    +          }
    +        )
    +        // If the operation timed out, throw a TimeoutException
    +        if (maybeResult.isEmpty) {
    +          throw new TimeoutException("Spark did not respond within the timeout period of " +
    +            transactionTimeout + "seconds. Transaction will be retried")
    +        }
    +        null
    +      } catch {
    +        case e: Throwable =>
    +          try {
    +            LOG.warn("Error while attempting to remove events from the channel.", e)
    +            tx.rollback()
    +          } catch {
    +            case e1: Throwable => LOG.error(
    +              "Rollback failed while attempting to rollback due to commit failure.", e1)
    +          }
    +          null // No point rethrowing the exception
    +      } finally {
    +        // Must *always* release the caller thread
    +        eventQueue.put(ErrorEventBatch)
    +        // In the case of success coming after the timeout, but before resetting the seq number
    +        // remove the event from the map and then clear the value
    +        resultQueue.clear()
    +        processorMap.remove(eventBatch.getSequenceNumber)
    +        processorFactory.get.checkIn(this)
    +        tx.close()
    +      }
    +    }
    +
    +    def toCharSequenceMap(inMap: java.util.Map[String, String]): java.util.Map[CharSequence,
    +      CharSequence] = {
    +      val charSeqMap = new util.HashMap[CharSequence, CharSequence](inMap.size())
    +      charSeqMap.putAll(inMap)
    +      charSeqMap
    +    }
    +  }
    +
    +  private class SparkHandlerFactory(val maxInstances: Int) {
    +    val queue = new scala.collection.mutable.Queue[TransactionProcessor]
    --- End diff --
    
    I will rename this to TransactionProcessorManager or something.


---
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 infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] spark pull request: SPARK-1729. Make Flume pull data from source, ...

Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the pull request:

    https://github.com/apache/spark/pull/807#issuecomment-43465538
  
     Merged build triggered. 


---
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 infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] spark pull request: SPARK-1729. Make Flume pull data from source, ...

Posted by tdas <gi...@git.apache.org>.
Github user tdas commented on the pull request:

    https://github.com/apache/spark/pull/807#issuecomment-49673187
  
    Jenkins, add to whitelist.



---
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 infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] spark pull request: [STREAMING] SPARK-1729. Make Flume pull data f...

Posted by tdas <gi...@git.apache.org>.
Github user tdas commented on the pull request:

    https://github.com/apache/spark/pull/807#issuecomment-50389912
  
    The binary compatibility test failed because it tried to compare current version of flume-sink with previous version (which does not exist). So we need to make an exclusion here. Let me figure this out with @pwendell 


---
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 infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] spark pull request: SPARK-1729. Make Flume pull data from source, ...

Posted by tdas <gi...@git.apache.org>.
Github user tdas commented on the pull request:

    https://github.com/apache/spark/pull/807#issuecomment-46257182
  
    @harishreedharan The SparkSink is looking quite good. Had more minor comments. I am yet to look at the Spark Streaming receiver side.  Let me know about instructions to run this code.


---
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 infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] spark pull request: SPARK-1729. Make Flume pull data from source, ...

Posted by harishreedharan <gi...@git.apache.org>.
Github user harishreedharan commented on a diff in the pull request:

    https://github.com/apache/spark/pull/807#discussion_r13471098
  
    --- Diff: external/flume-sink/src/main/scala/org/apache/spark/flume/sink/SparkSink.scala ---
    @@ -0,0 +1,392 @@
    +/*
    + * 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.flume.sink
    +
    +import org.apache.flume.sink.AbstractSink
    +import java.util.concurrent.locks.ReentrantLock
    +import org.apache.flume.Sink.Status
    +import org.apache.spark.flume.{SparkSinkEvent, EventBatch, SparkFlumeProtocol}
    +import scala.util.control.Breaks
    +import java.nio.ByteBuffer
    +import org.apache.flume.{FlumeException, Context}
    +import org.slf4j.LoggerFactory
    +import java.util.concurrent.atomic.AtomicLong
    +import org.apache.commons.lang.RandomStringUtils
    +import java.util.concurrent._
    +import java.util
    +import org.apache.flume.conf.{ConfigurationException, Configurable}
    +import com.google.common.util.concurrent.ThreadFactoryBuilder
    +import org.apache.avro.ipc.NettyServer
    +import org.apache.avro.ipc.specific.SpecificResponder
    +import java.net.InetSocketAddress
    +
    +class SparkSink() extends AbstractSink with Configurable {
    +  private val LOG = LoggerFactory.getLogger(this.getClass)
    +  private val lock = new ReentrantLock()
    +  private val blockingCondition = lock.newCondition()
    +
    +  // This sink will not persist sequence numbers and reuses them if it gets restarted.
    +  // So it is possible to commit a transaction which may have been meant for the sink before the
    +  // restart.
    +  // Since the new txn may not have the same sequence number we must guard against accidentally
    +  // committing
    +  // a new transaction. To reduce the probability of that happening a random string is prepended
    +  // to the sequence number.
    +  // Does not change for life of sink
    +  private val seqBase = RandomStringUtils.randomAlphanumeric(8)
    +  // Incremented for each transaction
    +  private val seqNum = new AtomicLong(0)
    +
    +  private var transactionExecutorOpt: Option[ExecutorService] = None
    +
    +  private var numProcessors: Integer = SparkSinkConfig.DEFAULT_PROCESSOR_COUNT
    +  private var transactionTimeout = SparkSinkConfig.DEFAULT_TRANSACTION_TIMEOUT
    +
    +  private val processorMap = new ConcurrentHashMap[CharSequence, TransactionProcessor]()
    +
    +  private var processorFactory: Option[SparkHandlerFactory] = None
    +  private var hostname: String = SparkSinkConfig.DEFAULT_HOSTNAME
    +  private var port: Int = 0
    +  private var maxThreads: Int = SparkSinkConfig.DEFAULT_MAX_THREADS
    +  private var serverOpt: Option[NettyServer] = None
    +  private var running = false
    +
    +  override def start() {
    +    transactionExecutorOpt = Option(Executors.newFixedThreadPool(numProcessors,
    +      new ThreadFactoryBuilder().setDaemon(true)
    +        .setNameFormat("Spark Sink, " + getName + " Processor Thread - %d").build()))
    +
    +    processorFactory = Option(new SparkHandlerFactory(numProcessors))
    +
    +    val responder = new SpecificResponder(classOf[SparkFlumeProtocol], new AvroCallbackHandler())
    +
    +    // Using the constructor that takes specific thread-pools requires bringing in netty
    +    // dependencies which are being excluded in the build. In practice,
    +    // Netty dependencies are already available on the JVM as Flume would have pulled them in.
    +    serverOpt = Option(new NettyServer(responder, new InetSocketAddress(hostname, port)))
    +
    +    serverOpt.map(server => server.start())
    +    lock.lock()
    +    try {
    +      running = true
    +    } finally {
    +      lock.unlock()
    +    }
    +    super.start()
    +  }
    +
    +  override def stop() {
    +    transactionExecutorOpt.map(executor => executor.shutdownNow())
    +    serverOpt.map(server => {
    +      server.close()
    +      server.join()
    +    })
    +    lock.lock()
    +    try {
    +      running = false
    +      blockingCondition.signalAll()
    +    } finally {
    +      lock.unlock()
    +    }
    +  }
    +
    +  override def configure(ctx: Context) {
    +    import SparkSinkConfig._
    +    hostname = ctx.getString(CONF_HOSTNAME, DEFAULT_HOSTNAME)
    +    val portOpt = Option(ctx.getInteger(CONF_PORT))
    +    if(portOpt.isDefined) {
    +      port = portOpt.get
    +    } else {
    +      throw new ConfigurationException("The Port to bind must be specified")
    +    }
    +    numProcessors = ctx.getInteger(PROCESSOR_COUNT, DEFAULT_PROCESSOR_COUNT)
    +    transactionTimeout = ctx.getInteger(CONF_TRANSACTION_TIMEOUT, DEFAULT_TRANSACTION_TIMEOUT)
    +    maxThreads = ctx.getInteger(CONF_MAX_THREADS, DEFAULT_MAX_THREADS)
    +  }
    +
    +  override def process(): Status = {
    +    // This method is called in a loop by the Flume framework - block it until the sink is
    +    // stopped to save CPU resources
    +    lock.lock()
    +    try {
    +      while(running) {
    +        blockingCondition.await()
    +      }
    +    } finally {
    +      lock.unlock()
    +    }
    +    Status.BACKOFF
    +  }
    +
    +
    +  // Object representing an empty batch returned by the txn processor due to some error.
    +  case object ErrorEventBatch extends EventBatch
    +
    +  private class AvroCallbackHandler() extends SparkFlumeProtocol {
    +
    +    override def getEventBatch(n: Int): EventBatch = {
    +      val processor = processorFactory.get.checkOut(n)
    +      transactionExecutorOpt.map(executor => executor.submit(processor))
    +      // Wait until a batch is available - can be null if some error was thrown
    +      val eventBatch = processor.eventQueue.take()
    +      eventBatch match {
    +        case ErrorEventBatch => throw new FlumeException("Something went wrong. No events" +
    +          " retrieved from channel.")
    +        case events => {
    +          processorMap.put(events.getSequenceNumber, processor)
    +          if (LOG.isDebugEnabled) {
    +            LOG.debug("Sent " + events.getEventBatch.size() +
    +              " events with sequence number: " + events.getSequenceNumber)
    +          }
    +          events
    +        }
    +      }
    +    }
    +
    +    override def ack(sequenceNumber: CharSequence): Void = {
    +      completeTransaction(sequenceNumber, success = true)
    +      null
    +    }
    +
    +    override def nack(sequenceNumber: CharSequence): Void = {
    +      completeTransaction(sequenceNumber, success = false)
    +      LOG.info("Spark failed to commit transaction. Will reattempt events.")
    +      null
    +    }
    +
    +    def completeTransaction(sequenceNumber: CharSequence, success: Boolean) {
    +      val processorOpt = Option(processorMap.remove(sequenceNumber))
    +      if (processorOpt.isDefined) {
    +        val processor = processorOpt.get
    +        processor.resultQueueUpdateLock.lock()
    +        try {
    +          // Is the sequence number the same as the one the processor is processing? If not,
    +          // don't update {
    +          if (processor.eventBatch.getSequenceNumber.equals(sequenceNumber)) {
    +            processor.resultQueue.put(success)
    +          }
    +        } finally {
    +          processor.resultQueueUpdateLock.unlock()
    +        }
    +      }
    +    }
    +  }
    +
    +  // Flume forces transactions to be thread-local (horrible, I know!)
    +  // So the sink basically spawns a new thread to pull the events out within a transaction.
    +  // The thread fills in the event batch object that is set before the thread is scheduled.
    +  // After filling it in, the thread waits on a condition - which is released only
    +  // when the success message comes back for the specific sequence number for that event batch.
    +  /**
    +   * This class represents a transaction on the Flume channel. This class runs a separate thread
    +   * which owns the transaction. It is blocked until the success call for that transaction comes
    +   * back.
    +   * @param maxBatchSize
    +   */
    +  private class TransactionProcessor(var maxBatchSize: Int) extends Callable[Void] {
    +    // Must be set to a new event batch before scheduling this!!
    +    val eventBatch = new EventBatch("", new util.LinkedList[SparkSinkEvent])
    +    val eventQueue = new SynchronousQueue[EventBatch]()
    +    val resultQueue = new SynchronousQueue[Boolean]()
    +    val resultQueueUpdateLock = new ReentrantLock()
    +
    +    object Zero {
    +      val zero = "0" // Oh, I miss static finals
    +    }
    +
    +
    +    override def call(): Void = {
    +      val tx = getChannel.getTransaction
    +      tx.begin()
    +      try {
    +        eventBatch.setSequenceNumber(seqBase + seqNum.incrementAndGet())
    +        val events = eventBatch.getEventBatch
    +        events.clear()
    +        val loop = new Breaks
    +        var gotEventsInThisTxn = false
    +        loop.breakable {
    +          var i = 0
    +          // Using for here causes the maxBatchSize change to be ineffective as the Range gets
    +          // pregenerated
    +          while (i < maxBatchSize) {
    +            i += 1
    +            val eventOpt = Option(getChannel.take())
    +            eventOpt.map(event => {
    +              events.add(new SparkSinkEvent(toCharSequenceMap(event
    +                .getHeaders),
    +                ByteBuffer.wrap(event.getBody)))
    +              gotEventsInThisTxn = true
    +            })
    +            if (eventOpt.isEmpty) {
    +              if (!gotEventsInThisTxn) {
    +                // To avoid sending empty batches, we wait till events are available backing off
    +                // between attempts to get events. Each attempt to get an event though causes one
    +                // iteration to be lost. To ensure that we still send back maxBatchSize number of
    +                // events, we cheat and increase the maxBatchSize by 1 to account for the lost
    +                // iteration. Even throwing an exception is expensive as Avro will serialize it
    +                // and send it over the wire, which is useless. Before incrementing though,
    +                // ensure that we are not anywhere near INT_MAX.
    +                if (maxBatchSize >= Int.MaxValue / 2) {
    --- End diff --
    
    Yep, a slightly modified version of this should be good (return when eventOpt is empty). 


---
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 infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] spark pull request: SPARK-1729. Make Flume pull data from source, ...

Posted by pwendell <gi...@git.apache.org>.
Github user pwendell commented on a diff in the pull request:

    https://github.com/apache/spark/pull/807#discussion_r13825922
  
    --- Diff: external/flume/src/main/scala/org/apache/spark/streaming/flume/EventTransformer.scala ---
    @@ -0,0 +1,72 @@
    +/*
    + * 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.streaming.flume
    +
    +import java.io.{ObjectOutput, ObjectInput}
    +
    +import scala.collection.JavaConversions._
    +
    +import org.apache.spark.util.Utils
    +import org.apache.spark.Logging
    +
    +/**
    + * A simple object that provides the implementation of readExternal and writeExternal for both
    + * the wrapper classes for Flume-style Events.
    + */
    +object EventTransformer extends Logging {
    +  def readExternal(in: ObjectInput): (java.util.HashMap[CharSequence, CharSequence],
    +    Array[Byte]) = {
    +    val bodyLength = in.readInt()
    +    val bodyBuff = new Array[Byte](bodyLength)
    +    in.read(bodyBuff)
    +
    +    val numHeaders = in.readInt()
    +    val headers = new java.util.HashMap[CharSequence, CharSequence]
    +
    +    for (i <- 0 until numHeaders) {
    +      val keyLength = in.readInt()
    +      val keyBuff = new Array[Byte](keyLength)
    +      in.read(keyBuff)
    --- End diff --
    
    The existing code does a `readFully` so your code actually introduces a bug here:
    
    https://github.com/apache/spark/blob/master/external/flume/src/main/scala/org/apache/spark/streaming/flume/FlumeInputDStream.scala#L74


---
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 infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] spark pull request: SPARK-1729. Make Flume pull data from source, ...

Posted by harishreedharan <gi...@git.apache.org>.
Github user harishreedharan commented on a diff in the pull request:

    https://github.com/apache/spark/pull/807#discussion_r13900807
  
    --- Diff: external/flume-sink/src/main/scala/org/apache/spark/flume/sink/SparkSink.scala ---
    @@ -0,0 +1,432 @@
    +/*
    + * 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.flume.sink
    +
    +import java.net.InetSocketAddress
    +import java.nio.ByteBuffer
    +import java.util
    +import java.util.concurrent._
    +import java.util.concurrent.atomic.AtomicLong
    +
    +import scala.util.control.Breaks
    +
    +import com.google.common.util.concurrent.ThreadFactoryBuilder
    +import org.apache.avro.ipc.NettyServer
    +import org.apache.avro.ipc.specific.SpecificResponder
    +import org.apache.commons.lang.RandomStringUtils
    +import org.apache.flume.Sink.Status
    +import org.apache.flume.conf.{ConfigurationException, Configurable}
    +import org.apache.flume.sink.AbstractSink
    +import org.apache.flume.{Channel, Transaction, FlumeException, Context}
    +import org.slf4j.LoggerFactory
    +
    +import org.apache.spark.flume.{SparkSinkEvent, EventBatch, SparkFlumeProtocol}
    +
    +/**
    + * A sink that uses Avro RPC to run a server that can be polled by Spark's
    + * FlumePollingInputDStream. This sink has the following configuration parameters:
    + *
    + * hostname - The hostname to bind to. Default: 0.0.0.0
    + * port - The port to bind to. (No default - mandatory)
    + * timeout - Time in seconds after which a transaction is rolled back,
    + * if an ACK is not received from Spark within that time
    + * threads - Number of threads to use to receive requests from Spark (Default: 10)
    + *
    + */
    +// Flume forces transactions to be thread-local. So each transaction *must* be committed, or
    +// rolled back from the thread it was originally created in. So each getEvents call from Spark
    +// creates a TransactionProcessor which runs in a new thread, in which the transaction is created
    +// and events are pulled off the channel. Once the events are sent to spark,
    +// that thread is blocked and the TransactionProcessor is saved in a map,
    +// until an ACK or NACK comes back or the transaction times out (after the specified timeout).
    +// When the response comes, the TransactionProcessor is retrieved and then unblocked,
    +// at which point the transaction is committed or rolled back.
    +class SparkSink extends AbstractSink with Configurable {
    +
    +  // Size of the pool to use for holding transaction processors.
    +  private var poolSize: Integer = SparkSinkConfig.DEFAULT_THREADS
    +
    +  // Timeout for each transaction. If spark does not respond in this much time,
    +  // rollback the transaction
    +  private var transactionTimeout = SparkSinkConfig.DEFAULT_TRANSACTION_TIMEOUT
    +
    +  // Address info to bind on
    +  private var hostname: String = SparkSinkConfig.DEFAULT_HOSTNAME
    +  private var port: Int = 0
    +
    +  // Handle to the server
    +  private var serverOpt: Option[NettyServer] = None
    +
    +  // The handler that handles the callback from Avro
    +  private var handler: Option[SparkAvroCallbackHandler] = None
    +
    +  // Latch that blocks off the Flume framework from wasting 1 thread.
    +  private val blockingLatch = new CountDownLatch(1)
    +
    +  override def start() {
    +    handler = Option(new SparkAvroCallbackHandler(poolSize, getChannel, transactionTimeout))
    +    val responder = new SpecificResponder(classOf[SparkFlumeProtocol], handler.get)
    +    // Using the constructor that takes specific thread-pools requires bringing in netty
    +    // dependencies which are being excluded in the build. In practice,
    +    // Netty dependencies are already available on the JVM as Flume would have pulled them in.
    +    serverOpt = Option(new NettyServer(responder, new InetSocketAddress(hostname, port)))
    +    serverOpt.map(server => {
    +      server.start()
    +    })
    +    super.start()
    +  }
    +
    +  override def stop() {
    +    handler.map(callbackHandler => {
    +      callbackHandler.shutdown()
    +    })
    +    serverOpt.map(server => {
    +      server.close()
    +      server.join()
    +    })
    +    blockingLatch.countDown()
    +    super.stop()
    +  }
    +
    +  /**
    +   * @param ctx
    +   */
    +  override def configure(ctx: Context) {
    +    import SparkSinkConfig._
    +    hostname = ctx.getString(CONF_HOSTNAME, DEFAULT_HOSTNAME)
    +    port = Option(ctx.getInteger(CONF_PORT)).
    +      getOrElse(throw new ConfigurationException("The port to bind to must be specified"))
    +    poolSize = ctx.getInteger(THREADS, DEFAULT_THREADS)
    +    transactionTimeout = ctx.getInteger(CONF_TRANSACTION_TIMEOUT, DEFAULT_TRANSACTION_TIMEOUT)
    +  }
    +
    +  override def process(): Status = {
    +    // This method is called in a loop by the Flume framework - block it until the sink is
    +    // stopped to save CPU resources. The sink runner will interrupt this thread when the sink is
    +    // being shut down.
    +    blockingLatch.await()
    +    Status.BACKOFF
    +  }
    +}
    +
    +/**
    + * Class that implements the SparkFlumeProtocol, that is used by the Avro Netty Server to process
    + * requests. Each getEvents, ack and nack call is forwarded to an instance of this class.
    + * @param threads Number of threads to use to process requests.
    + * @param channel The channel that the sink pulls events from
    + * @param transactionTimeout Timeout in millis after which the transaction if not acked by Spark
    + *                           is rolled back.
    + */
    +private class SparkAvroCallbackHandler(val threads: Int, val channel: Channel,
    +  val transactionTimeout: Int) extends SparkFlumeProtocol {
    +  private val LOG = LoggerFactory.getLogger(classOf[SparkAvroCallbackHandler])
    +  val transactionExecutorOpt = Option(Executors.newFixedThreadPool(threads,
    +    new ThreadFactoryBuilder().setDaemon(true)
    +      .setNameFormat("Spark Sink Processor Thread - %d").build()))
    +  private val processorMap = new ConcurrentHashMap[CharSequence, TransactionProcessor]()
    +  // This sink will not persist sequence numbers and reuses them if it gets restarted.
    +  // So it is possible to commit a transaction which may have been meant for the sink before the
    +  // restart.
    +  // Since the new txn may not have the same sequence number we must guard against accidentally
    +  // committing a new transaction. To reduce the probability of that happening a random string is
    +  // prepended to the sequence number. Does not change for life of sink
    +  private val seqBase = RandomStringUtils.randomAlphanumeric(8)
    +  private val seqCounter = new AtomicLong(0)
    +
    +  /**
    +   * Returns a bunch of events to Spark over Avro RPC.
    +   * @param n Maximum number of events to return in a batch
    +   * @return [[EventBatch]] instance that has a sequence number and an array of at most n events
    +   */
    +  override def getEventBatch(n: Int): EventBatch = {
    +    val sequenceNumber = seqBase + seqCounter.incrementAndGet()
    +    val processor = new TransactionProcessor(channel, sequenceNumber,
    +      n, transactionTimeout, this)
    +    transactionExecutorOpt.map(executor => {
    +      executor.submit(processor)
    +    })
    +    // Wait until a batch is available - can be null if some error was thrown
    +    processor.getEventBatch match {
    +      case ErrorEventBatch => throw new FlumeException("Something went wrong. No events" +
    +        " retrieved from channel.")
    +      case eventBatch: EventBatch =>
    +        processorMap.put(sequenceNumber, processor)
    +        if (LOG.isDebugEnabled()) {
    +          LOG.debug("Sent " + eventBatch.getEvents.size() +
    +            " events with sequence number: " + eventBatch.getSequenceNumber)
    +        }
    +        eventBatch
    +    }
    +  }
    +
    +  /**
    +   * Called by Spark to indicate successful commit of a batch
    +   * @param sequenceNumber The sequence number of the event batch that was successful
    +   */
    +  override def ack(sequenceNumber: CharSequence): Void = {
    +    completeTransaction(sequenceNumber, success = true)
    +    null
    +  }
    +
    +  /**
    +   * Called by Spark to indicate failed commit of a batch
    +   * @param sequenceNumber The sequence number of the event batch that failed
    +   * @return
    +   */
    +  override def nack(sequenceNumber: CharSequence): Void = {
    +    completeTransaction(sequenceNumber, success = false)
    +    LOG.info("Spark failed to commit transaction. Will reattempt events.")
    +    null
    +  }
    +
    +  /**
    +   * Helper method to commit or rollback a transaction.
    +   * @param sequenceNumber The sequence number of the batch that was completed
    +   * @param success Whether the batch was successful or not.
    +   */
    +  private def completeTransaction(sequenceNumber: CharSequence, success: Boolean) {
    +    Option(removeAndGetProcessor(sequenceNumber)).map(processor => {
    +      processor.batchProcessed(success)
    +    })
    +  }
    +
    +  /**
    +   * Helper method to remove the TxnProcessor for a Sequence Number. Can be used to avoid a leak.
    +   * @param sequenceNumber
    +   * @return The transaction processor for the corresponding batch. Note that this instance is no
    +   *         longer tracked and the caller is responsible for that txn processor.
    +   */
    +  private[flume] def removeAndGetProcessor(sequenceNumber: CharSequence): TransactionProcessor = {
    +    processorMap.remove(sequenceNumber.toString) // The toString is required!
    +  }
    +
    +  /**
    +   * Shuts down the executor used to process transactions.
    +   */
    +  def shutdown() {
    +    transactionExecutorOpt.map(executor => {
    +      executor.shutdownNow()
    +    })
    +  }
    +}
    +
    +/**
    + * Object representing an empty batch returned by the txn processor due to some error.
    + */
    +case object ErrorEventBatch extends EventBatch
    --- End diff --
    
    I had to change this a bit, since Avro will serialize only fields represented by the message and not new fields in the subclass. Avro also does not support inheritance, so I added an additional field in the batch to show if it is an error or not. If the value is empty, then it means that it is a valid batch. If it is not, that value is used as the error message in the log on the Spark side


---
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 infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] spark pull request: [STREAMING] SPARK-1729. Make Flume pull data f...

Posted by harishreedharan <gi...@git.apache.org>.
Github user harishreedharan commented on the pull request:

    https://github.com/apache/spark/pull/807#issuecomment-50433240
  
    `SparkSQLOperationManager` and `HadoopTableReader` were added to ASF git master. Since the github mirror is out of sync, the merge commit between this PR and that one makes the Jenkins script think that this PR added these two classes.


---
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 infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] spark pull request: SPARK-1729. Make Flume pull data from source, ...

Posted by rxin <gi...@git.apache.org>.
Github user rxin commented on the pull request:

    https://github.com/apache/spark/pull/807#issuecomment-43465463
  
    Jenkins, test this please.


---
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 infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] spark pull request: SPARK-1729. Make Flume pull data from source, ...

Posted by harishreedharan <gi...@git.apache.org>.
Github user harishreedharan commented on the pull request:

    https://github.com/apache/spark/pull/807#issuecomment-43524979
  
    Thanks for the comments @srowen!


---
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 infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] spark pull request: SPARK-1729. Make Flume pull data from source, ...

Posted by harishreedharan <gi...@git.apache.org>.
Github user harishreedharan commented on a diff in the pull request:

    https://github.com/apache/spark/pull/807#discussion_r13466181
  
    --- Diff: external/flume-sink/src/main/scala/org/apache/spark/flume/sink/SparkSink.scala ---
    @@ -0,0 +1,392 @@
    +/*
    + * 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.flume.sink
    +
    +import org.apache.flume.sink.AbstractSink
    +import java.util.concurrent.locks.ReentrantLock
    +import org.apache.flume.Sink.Status
    +import org.apache.spark.flume.{SparkSinkEvent, EventBatch, SparkFlumeProtocol}
    +import scala.util.control.Breaks
    +import java.nio.ByteBuffer
    +import org.apache.flume.{FlumeException, Context}
    +import org.slf4j.LoggerFactory
    +import java.util.concurrent.atomic.AtomicLong
    +import org.apache.commons.lang.RandomStringUtils
    +import java.util.concurrent._
    +import java.util
    +import org.apache.flume.conf.{ConfigurationException, Configurable}
    +import com.google.common.util.concurrent.ThreadFactoryBuilder
    +import org.apache.avro.ipc.NettyServer
    +import org.apache.avro.ipc.specific.SpecificResponder
    +import java.net.InetSocketAddress
    +
    +class SparkSink() extends AbstractSink with Configurable {
    +  private val LOG = LoggerFactory.getLogger(this.getClass)
    +  private val lock = new ReentrantLock()
    +  private val blockingCondition = lock.newCondition()
    +
    +  // This sink will not persist sequence numbers and reuses them if it gets restarted.
    +  // So it is possible to commit a transaction which may have been meant for the sink before the
    +  // restart.
    +  // Since the new txn may not have the same sequence number we must guard against accidentally
    +  // committing
    +  // a new transaction. To reduce the probability of that happening a random string is prepended
    +  // to the sequence number.
    +  // Does not change for life of sink
    +  private val seqBase = RandomStringUtils.randomAlphanumeric(8)
    +  // Incremented for each transaction
    +  private val seqNum = new AtomicLong(0)
    +
    +  private var transactionExecutorOpt: Option[ExecutorService] = None
    +
    +  private var numProcessors: Integer = SparkSinkConfig.DEFAULT_PROCESSOR_COUNT
    +  private var transactionTimeout = SparkSinkConfig.DEFAULT_TRANSACTION_TIMEOUT
    +
    +  private val processorMap = new ConcurrentHashMap[CharSequence, TransactionProcessor]()
    +
    +  private var processorFactory: Option[SparkHandlerFactory] = None
    +  private var hostname: String = SparkSinkConfig.DEFAULT_HOSTNAME
    +  private var port: Int = 0
    +  private var maxThreads: Int = SparkSinkConfig.DEFAULT_MAX_THREADS
    +  private var serverOpt: Option[NettyServer] = None
    +  private var running = false
    +
    +  override def start() {
    +    transactionExecutorOpt = Option(Executors.newFixedThreadPool(numProcessors,
    +      new ThreadFactoryBuilder().setDaemon(true)
    +        .setNameFormat("Spark Sink, " + getName + " Processor Thread - %d").build()))
    +
    +    processorFactory = Option(new SparkHandlerFactory(numProcessors))
    +
    +    val responder = new SpecificResponder(classOf[SparkFlumeProtocol], new AvroCallbackHandler())
    +
    +    // Using the constructor that takes specific thread-pools requires bringing in netty
    +    // dependencies which are being excluded in the build. In practice,
    +    // Netty dependencies are already available on the JVM as Flume would have pulled them in.
    +    serverOpt = Option(new NettyServer(responder, new InetSocketAddress(hostname, port)))
    +
    +    serverOpt.map(server => server.start())
    +    lock.lock()
    +    try {
    +      running = true
    +    } finally {
    +      lock.unlock()
    +    }
    +    super.start()
    +  }
    +
    +  override def stop() {
    +    transactionExecutorOpt.map(executor => executor.shutdownNow())
    +    serverOpt.map(server => {
    +      server.close()
    +      server.join()
    +    })
    +    lock.lock()
    +    try {
    +      running = false
    +      blockingCondition.signalAll()
    +    } finally {
    +      lock.unlock()
    +    }
    +  }
    +
    +  override def configure(ctx: Context) {
    +    import SparkSinkConfig._
    +    hostname = ctx.getString(CONF_HOSTNAME, DEFAULT_HOSTNAME)
    +    val portOpt = Option(ctx.getInteger(CONF_PORT))
    +    if(portOpt.isDefined) {
    +      port = portOpt.get
    +    } else {
    +      throw new ConfigurationException("The Port to bind must be specified")
    +    }
    +    numProcessors = ctx.getInteger(PROCESSOR_COUNT, DEFAULT_PROCESSOR_COUNT)
    +    transactionTimeout = ctx.getInteger(CONF_TRANSACTION_TIMEOUT, DEFAULT_TRANSACTION_TIMEOUT)
    +    maxThreads = ctx.getInteger(CONF_MAX_THREADS, DEFAULT_MAX_THREADS)
    +  }
    +
    +  override def process(): Status = {
    +    // This method is called in a loop by the Flume framework - block it until the sink is
    +    // stopped to save CPU resources
    +    lock.lock()
    +    try {
    +      while(running) {
    +        blockingCondition.await()
    +      }
    +    } finally {
    +      lock.unlock()
    +    }
    +    Status.BACKOFF
    +  }
    +
    +
    +  // Object representing an empty batch returned by the txn processor due to some error.
    +  case object ErrorEventBatch extends EventBatch
    +
    +  private class AvroCallbackHandler() extends SparkFlumeProtocol {
    +
    +    override def getEventBatch(n: Int): EventBatch = {
    +      val processor = processorFactory.get.checkOut(n)
    +      transactionExecutorOpt.map(executor => executor.submit(processor))
    +      // Wait until a batch is available - can be null if some error was thrown
    +      val eventBatch = processor.eventQueue.take()
    +      eventBatch match {
    +        case ErrorEventBatch => throw new FlumeException("Something went wrong. No events" +
    +          " retrieved from channel.")
    +        case events => {
    +          processorMap.put(events.getSequenceNumber, processor)
    +          if (LOG.isDebugEnabled) {
    +            LOG.debug("Sent " + events.getEventBatch.size() +
    +              " events with sequence number: " + events.getSequenceNumber)
    +          }
    +          events
    +        }
    +      }
    +    }
    +
    +    override def ack(sequenceNumber: CharSequence): Void = {
    +      completeTransaction(sequenceNumber, success = true)
    +      null
    +    }
    +
    +    override def nack(sequenceNumber: CharSequence): Void = {
    +      completeTransaction(sequenceNumber, success = false)
    +      LOG.info("Spark failed to commit transaction. Will reattempt events.")
    +      null
    +    }
    +
    +    def completeTransaction(sequenceNumber: CharSequence, success: Boolean) {
    +      val processorOpt = Option(processorMap.remove(sequenceNumber))
    +      if (processorOpt.isDefined) {
    +        val processor = processorOpt.get
    +        processor.resultQueueUpdateLock.lock()
    +        try {
    +          // Is the sequence number the same as the one the processor is processing? If not,
    +          // don't update {
    +          if (processor.eventBatch.getSequenceNumber.equals(sequenceNumber)) {
    +            processor.resultQueue.put(success)
    +          }
    +        } finally {
    +          processor.resultQueueUpdateLock.unlock()
    +        }
    +      }
    +    }
    +  }
    +
    +  // Flume forces transactions to be thread-local (horrible, I know!)
    +  // So the sink basically spawns a new thread to pull the events out within a transaction.
    +  // The thread fills in the event batch object that is set before the thread is scheduled.
    +  // After filling it in, the thread waits on a condition - which is released only
    +  // when the success message comes back for the specific sequence number for that event batch.
    +  /**
    +   * This class represents a transaction on the Flume channel. This class runs a separate thread
    +   * which owns the transaction. It is blocked until the success call for that transaction comes
    +   * back.
    +   * @param maxBatchSize
    +   */
    +  private class TransactionProcessor(var maxBatchSize: Int) extends Callable[Void] {
    +    // Must be set to a new event batch before scheduling this!!
    +    val eventBatch = new EventBatch("", new util.LinkedList[SparkSinkEvent])
    +    val eventQueue = new SynchronousQueue[EventBatch]()
    +    val resultQueue = new SynchronousQueue[Boolean]()
    +    val resultQueueUpdateLock = new ReentrantLock()
    +
    +    object Zero {
    +      val zero = "0" // Oh, I miss static finals
    +    }
    +
    +
    +    override def call(): Void = {
    +      val tx = getChannel.getTransaction
    +      tx.begin()
    +      try {
    +        eventBatch.setSequenceNumber(seqBase + seqNum.incrementAndGet())
    +        val events = eventBatch.getEventBatch
    +        events.clear()
    +        val loop = new Breaks
    +        var gotEventsInThisTxn = false
    +        loop.breakable {
    +          var i = 0
    +          // Using for here causes the maxBatchSize change to be ineffective as the Range gets
    +          // pregenerated
    +          while (i < maxBatchSize) {
    +            i += 1
    +            val eventOpt = Option(getChannel.take())
    +            eventOpt.map(event => {
    +              events.add(new SparkSinkEvent(toCharSequenceMap(event
    +                .getHeaders),
    +                ByteBuffer.wrap(event.getBody)))
    +              gotEventsInThisTxn = true
    +            })
    +            if (eventOpt.isEmpty) {
    +              if (!gotEventsInThisTxn) {
    +                // To avoid sending empty batches, we wait till events are available backing off
    +                // between attempts to get events. Each attempt to get an event though causes one
    +                // iteration to be lost. To ensure that we still send back maxBatchSize number of
    +                // events, we cheat and increase the maxBatchSize by 1 to account for the lost
    +                // iteration. Even throwing an exception is expensive as Avro will serialize it
    +                // and send it over the wire, which is useless. Before incrementing though,
    +                // ensure that we are not anywhere near INT_MAX.
    +                if (maxBatchSize >= Int.MaxValue / 2) {
    +                  // Random sanity check
    +                  throw new RuntimeException("Safety exception - polled too many times, no events!")
    +                }
    +                maxBatchSize += 1
    +                Thread.sleep(500)
    +              } else {
    +                loop.break()
    +              }
    +            }
    +          }
    +        }
    +        // Make the data available to the sender thread
    +        eventQueue.put(eventBatch)
    +
    +        // Wait till timeout for the ack/nack
    +        val maybeResult = Option(resultQueue.poll(transactionTimeout, TimeUnit.SECONDS))
    +        // There is a race condition here.
    +        // 1. This times out.
    +        // 2. The result is empty, so timeout exception is thrown.
    +        // 3. The ack comes in before the finally block is entered
    +        // 4. The thread with the ack has a handle to this processor,
    +        // and another thread has the same processor checked out
    +        // (since the finally block was executed and the processor checked back in)
    +        // 5. The thread with the ack now updates the result queue,
    +        // so the processor thinks it is the ack for the current batch.
    +        // To avoid this - update the sequence number to "0" (with or without a result - does not
    +        // matter).
    +        // In the ack method, check if the seq number is the same as the processor's -
    +        // if they are then update the result queue. Now if the
    +        // processor updates the seq number first - the ack/nack never updates the result. If the
    +        // ack/nack updates the
    +        // result after the timeout but before the seq number is updated to "0" it does not
    +        // matter - the processor would
    +        // still timeout and the result is cleared before reusing the processor.
    +        // Unfortunately, this needs to be done from within a lock
    +        // to make sure that the new sequence number is actually visible to the ack thread
    +        // (happens-before)
    +        resultQueueUpdateLock.lock()
    +        try {
    +          eventBatch.setSequenceNumber(Zero.zero)
    +        } finally {
    +          resultQueueUpdateLock.unlock()
    +        }
    +        eventBatch.getEventBatch.clear()
    +        // If the batch failed on spark side, throw a FlumeException
    +        maybeResult.map(success =>
    +          if (!success) {
    +            throw new
    +                FlumeException("Spark could not accept events. The transaction will be retried.")
    +          }
    +        )
    +        // If the operation timed out, throw a TimeoutException
    +        if (maybeResult.isEmpty) {
    +          throw new TimeoutException("Spark did not respond within the timeout period of " +
    +            transactionTimeout + "seconds. Transaction will be retried")
    +        }
    +        null
    +      } catch {
    +        case e: Throwable =>
    +          try {
    +            LOG.warn("Error while attempting to remove events from the channel.", e)
    +            tx.rollback()
    +          } catch {
    +            case e1: Throwable => LOG.error(
    +              "Rollback failed while attempting to rollback due to commit failure.", e1)
    +          }
    +          null // No point rethrowing the exception
    +      } finally {
    +        // Must *always* release the caller thread
    +        eventQueue.put(ErrorEventBatch)
    +        // In the case of success coming after the timeout, but before resetting the seq number
    +        // remove the event from the map and then clear the value
    +        resultQueue.clear()
    +        processorMap.remove(eventBatch.getSequenceNumber)
    +        processorFactory.get.checkIn(this)
    +        tx.close()
    +      }
    +    }
    +
    +    def toCharSequenceMap(inMap: java.util.Map[String, String]): java.util.Map[CharSequence,
    +      CharSequence] = {
    +      val charSeqMap = new util.HashMap[CharSequence, CharSequence](inMap.size())
    +      charSeqMap.putAll(inMap)
    +      charSeqMap
    +    }
    +  }
    +
    +  private class SparkHandlerFactory(val maxInstances: Int) {
    +    val queue = new scala.collection.mutable.Queue[TransactionProcessor]
    +    val queueModificationLock = new ReentrantLock()
    +    var currentSize = 0
    +    val waitForCheckIn = queueModificationLock.newCondition()
    +
    +    def checkOut(n: Int): TransactionProcessor = {
    +      def getProcessor = {
    +        val processor = queue.dequeue()
    +        processor.maxBatchSize = n
    +        processor
    +      }
    +      queueModificationLock.lock()
    +      try {
    +        if (queue.size > 0) {
    +          getProcessor
    +        }
    +        else {
    +          if (currentSize < maxInstances) {
    +            currentSize += 1
    --- End diff --
    
    The idea is to create instances of processors only when required (basically if the maxInstances is 10, but only 2 are used simultaneously. we only create 2). So create instances upto maxInstances. currentSize tracks total number of instances that have been created till now.


---
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 infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] spark pull request: SPARK-1729. Make Flume pull data from source, ...

Posted by tdas <gi...@git.apache.org>.
Github user tdas commented on a diff in the pull request:

    https://github.com/apache/spark/pull/807#discussion_r13466106
  
    --- Diff: external/flume-sink/src/main/scala/org/apache/spark/flume/sink/SparkSink.scala ---
    @@ -0,0 +1,392 @@
    +/*
    + * 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.flume.sink
    +
    +import org.apache.flume.sink.AbstractSink
    +import java.util.concurrent.locks.ReentrantLock
    +import org.apache.flume.Sink.Status
    +import org.apache.spark.flume.{SparkSinkEvent, EventBatch, SparkFlumeProtocol}
    +import scala.util.control.Breaks
    +import java.nio.ByteBuffer
    +import org.apache.flume.{FlumeException, Context}
    +import org.slf4j.LoggerFactory
    +import java.util.concurrent.atomic.AtomicLong
    +import org.apache.commons.lang.RandomStringUtils
    +import java.util.concurrent._
    +import java.util
    +import org.apache.flume.conf.{ConfigurationException, Configurable}
    +import com.google.common.util.concurrent.ThreadFactoryBuilder
    +import org.apache.avro.ipc.NettyServer
    +import org.apache.avro.ipc.specific.SpecificResponder
    +import java.net.InetSocketAddress
    +
    +class SparkSink() extends AbstractSink with Configurable {
    +  private val LOG = LoggerFactory.getLogger(this.getClass)
    +  private val lock = new ReentrantLock()
    +  private val blockingCondition = lock.newCondition()
    +
    +  // This sink will not persist sequence numbers and reuses them if it gets restarted.
    +  // So it is possible to commit a transaction which may have been meant for the sink before the
    +  // restart.
    +  // Since the new txn may not have the same sequence number we must guard against accidentally
    +  // committing
    +  // a new transaction. To reduce the probability of that happening a random string is prepended
    +  // to the sequence number.
    +  // Does not change for life of sink
    +  private val seqBase = RandomStringUtils.randomAlphanumeric(8)
    +  // Incremented for each transaction
    +  private val seqNum = new AtomicLong(0)
    +
    +  private var transactionExecutorOpt: Option[ExecutorService] = None
    +
    +  private var numProcessors: Integer = SparkSinkConfig.DEFAULT_PROCESSOR_COUNT
    +  private var transactionTimeout = SparkSinkConfig.DEFAULT_TRANSACTION_TIMEOUT
    +
    +  private val processorMap = new ConcurrentHashMap[CharSequence, TransactionProcessor]()
    +
    +  private var processorFactory: Option[SparkHandlerFactory] = None
    +  private var hostname: String = SparkSinkConfig.DEFAULT_HOSTNAME
    +  private var port: Int = 0
    +  private var maxThreads: Int = SparkSinkConfig.DEFAULT_MAX_THREADS
    +  private var serverOpt: Option[NettyServer] = None
    +  private var running = false
    +
    +  override def start() {
    +    transactionExecutorOpt = Option(Executors.newFixedThreadPool(numProcessors,
    +      new ThreadFactoryBuilder().setDaemon(true)
    +        .setNameFormat("Spark Sink, " + getName + " Processor Thread - %d").build()))
    +
    +    processorFactory = Option(new SparkHandlerFactory(numProcessors))
    +
    +    val responder = new SpecificResponder(classOf[SparkFlumeProtocol], new AvroCallbackHandler())
    +
    +    // Using the constructor that takes specific thread-pools requires bringing in netty
    +    // dependencies which are being excluded in the build. In practice,
    +    // Netty dependencies are already available on the JVM as Flume would have pulled them in.
    +    serverOpt = Option(new NettyServer(responder, new InetSocketAddress(hostname, port)))
    +
    +    serverOpt.map(server => server.start())
    +    lock.lock()
    +    try {
    +      running = true
    +    } finally {
    +      lock.unlock()
    +    }
    +    super.start()
    +  }
    +
    +  override def stop() {
    +    transactionExecutorOpt.map(executor => executor.shutdownNow())
    +    serverOpt.map(server => {
    +      server.close()
    +      server.join()
    +    })
    +    lock.lock()
    +    try {
    +      running = false
    +      blockingCondition.signalAll()
    +    } finally {
    +      lock.unlock()
    +    }
    +  }
    +
    +  override def configure(ctx: Context) {
    +    import SparkSinkConfig._
    +    hostname = ctx.getString(CONF_HOSTNAME, DEFAULT_HOSTNAME)
    +    val portOpt = Option(ctx.getInteger(CONF_PORT))
    +    if(portOpt.isDefined) {
    +      port = portOpt.get
    +    } else {
    +      throw new ConfigurationException("The Port to bind must be specified")
    +    }
    +    numProcessors = ctx.getInteger(PROCESSOR_COUNT, DEFAULT_PROCESSOR_COUNT)
    +    transactionTimeout = ctx.getInteger(CONF_TRANSACTION_TIMEOUT, DEFAULT_TRANSACTION_TIMEOUT)
    +    maxThreads = ctx.getInteger(CONF_MAX_THREADS, DEFAULT_MAX_THREADS)
    +  }
    +
    +  override def process(): Status = {
    +    // This method is called in a loop by the Flume framework - block it until the sink is
    +    // stopped to save CPU resources
    +    lock.lock()
    +    try {
    +      while(running) {
    +        blockingCondition.await()
    +      }
    +    } finally {
    +      lock.unlock()
    +    }
    +    Status.BACKOFF
    +  }
    +
    +
    +  // Object representing an empty batch returned by the txn processor due to some error.
    +  case object ErrorEventBatch extends EventBatch
    +
    +  private class AvroCallbackHandler() extends SparkFlumeProtocol {
    --- End diff --
    
    Scala style nit: no need for parenthesis when no parameter present


---
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 infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] spark pull request: SPARK-1729. Make Flume pull data from source, ...

Posted by harishreedharan <gi...@git.apache.org>.
Github user harishreedharan commented on the pull request:

    https://github.com/apache/spark/pull/807#issuecomment-43470341
  
    Not sure why the build failed with a dependency resolution issue. It seems to work locally when I do sbt assembly locally. Does the order of modules specified in the build spec matter?
    
    Any advice from someone more familiar with sbt?
    
    > On May 18, 2014, at 10:19 PM, UCB AMPLab <no...@github.com> wrote:
    > 
    > Refer to this link for build results: https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/15074/
    > 
    > —
    > Reply to this email directly or view it on GitHub.


---
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 infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] spark pull request: SPARK-1729. Make Flume pull data from source, ...

Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the pull request:

    https://github.com/apache/spark/pull/807#issuecomment-43465544
  
    Merged build started. 


---
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 infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] spark pull request: [STREAMING] SPARK-1729. Make Flume pull data f...

Posted by SparkQA <gi...@git.apache.org>.
Github user SparkQA commented on the pull request:

    https://github.com/apache/spark/pull/807#issuecomment-50380439
  
    QA tests have started for PR 807. This patch merges cleanly. <br>View progress: https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/17298/consoleFull


---
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 infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] spark pull request: [STREAMING] SPARK-1729. Make Flume pull data f...

Posted by SparkQA <gi...@git.apache.org>.
Github user SparkQA commented on the pull request:

    https://github.com/apache/spark/pull/807#issuecomment-50432921
  
    QA results for PR 807:<br>- This patch PASSES unit tests.<br>- This patch merges cleanly<br>- This patch adds the following public classes (experimental):<br>class SparkSink extends AbstractSink with Logging with Configurable {<br>class SparkSQLOperationManager(hiveContext: HiveContext) extends OperationManager with Logging {<br>class HadoopTableReader(<br><br>For more information see test ouptut:<br>https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/17332/consoleFull


---
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 infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] spark pull request: SPARK-1729. Make Flume pull data from source, ...

Posted by tdas <gi...@git.apache.org>.
Github user tdas commented on a diff in the pull request:

    https://github.com/apache/spark/pull/807#discussion_r13466929
  
    --- Diff: external/flume-sink/src/main/scala/org/apache/spark/flume/sink/SparkSink.scala ---
    @@ -0,0 +1,392 @@
    +/*
    + * 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.flume.sink
    +
    +import org.apache.flume.sink.AbstractSink
    +import java.util.concurrent.locks.ReentrantLock
    +import org.apache.flume.Sink.Status
    +import org.apache.spark.flume.{SparkSinkEvent, EventBatch, SparkFlumeProtocol}
    +import scala.util.control.Breaks
    +import java.nio.ByteBuffer
    +import org.apache.flume.{FlumeException, Context}
    +import org.slf4j.LoggerFactory
    +import java.util.concurrent.atomic.AtomicLong
    +import org.apache.commons.lang.RandomStringUtils
    +import java.util.concurrent._
    +import java.util
    +import org.apache.flume.conf.{ConfigurationException, Configurable}
    +import com.google.common.util.concurrent.ThreadFactoryBuilder
    +import org.apache.avro.ipc.NettyServer
    +import org.apache.avro.ipc.specific.SpecificResponder
    +import java.net.InetSocketAddress
    +
    +class SparkSink() extends AbstractSink with Configurable {
    +  private val LOG = LoggerFactory.getLogger(this.getClass)
    +  private val lock = new ReentrantLock()
    +  private val blockingCondition = lock.newCondition()
    --- End diff --
    
    In that case, it best to synchronized rather than locks. Code stays cleaner and more concise. 


---
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 infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] spark pull request: SPARK-1729. Make Flume pull data from source, ...

Posted by harishreedharan <gi...@git.apache.org>.
Github user harishreedharan commented on a diff in the pull request:

    https://github.com/apache/spark/pull/807#discussion_r13473153
  
    --- Diff: external/flume-sink/src/main/scala/org/apache/spark/flume/sink/SparkSink.scala ---
    @@ -0,0 +1,392 @@
    +/*
    + * 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.flume.sink
    +
    +import org.apache.flume.sink.AbstractSink
    +import java.util.concurrent.locks.ReentrantLock
    +import org.apache.flume.Sink.Status
    +import org.apache.spark.flume.{SparkSinkEvent, EventBatch, SparkFlumeProtocol}
    +import scala.util.control.Breaks
    +import java.nio.ByteBuffer
    +import org.apache.flume.{FlumeException, Context}
    +import org.slf4j.LoggerFactory
    +import java.util.concurrent.atomic.AtomicLong
    +import org.apache.commons.lang.RandomStringUtils
    +import java.util.concurrent._
    +import java.util
    +import org.apache.flume.conf.{ConfigurationException, Configurable}
    +import com.google.common.util.concurrent.ThreadFactoryBuilder
    +import org.apache.avro.ipc.NettyServer
    +import org.apache.avro.ipc.specific.SpecificResponder
    +import java.net.InetSocketAddress
    +
    +class SparkSink() extends AbstractSink with Configurable {
    +  private val LOG = LoggerFactory.getLogger(this.getClass)
    +  private val lock = new ReentrantLock()
    +  private val blockingCondition = lock.newCondition()
    +
    +  // This sink will not persist sequence numbers and reuses them if it gets restarted.
    +  // So it is possible to commit a transaction which may have been meant for the sink before the
    +  // restart.
    +  // Since the new txn may not have the same sequence number we must guard against accidentally
    +  // committing
    +  // a new transaction. To reduce the probability of that happening a random string is prepended
    +  // to the sequence number.
    +  // Does not change for life of sink
    +  private val seqBase = RandomStringUtils.randomAlphanumeric(8)
    +  // Incremented for each transaction
    +  private val seqNum = new AtomicLong(0)
    +
    +  private var transactionExecutorOpt: Option[ExecutorService] = None
    +
    +  private var numProcessors: Integer = SparkSinkConfig.DEFAULT_PROCESSOR_COUNT
    +  private var transactionTimeout = SparkSinkConfig.DEFAULT_TRANSACTION_TIMEOUT
    +
    +  private val processorMap = new ConcurrentHashMap[CharSequence, TransactionProcessor]()
    +
    +  private var processorFactory: Option[SparkHandlerFactory] = None
    +  private var hostname: String = SparkSinkConfig.DEFAULT_HOSTNAME
    +  private var port: Int = 0
    +  private var maxThreads: Int = SparkSinkConfig.DEFAULT_MAX_THREADS
    +  private var serverOpt: Option[NettyServer] = None
    +  private var running = false
    +
    +  override def start() {
    +    transactionExecutorOpt = Option(Executors.newFixedThreadPool(numProcessors,
    +      new ThreadFactoryBuilder().setDaemon(true)
    +        .setNameFormat("Spark Sink, " + getName + " Processor Thread - %d").build()))
    +
    +    processorFactory = Option(new SparkHandlerFactory(numProcessors))
    +
    +    val responder = new SpecificResponder(classOf[SparkFlumeProtocol], new AvroCallbackHandler())
    +
    +    // Using the constructor that takes specific thread-pools requires bringing in netty
    +    // dependencies which are being excluded in the build. In practice,
    +    // Netty dependencies are already available on the JVM as Flume would have pulled them in.
    +    serverOpt = Option(new NettyServer(responder, new InetSocketAddress(hostname, port)))
    +
    +    serverOpt.map(server => server.start())
    +    lock.lock()
    +    try {
    +      running = true
    +    } finally {
    +      lock.unlock()
    +    }
    +    super.start()
    +  }
    +
    +  override def stop() {
    +    transactionExecutorOpt.map(executor => executor.shutdownNow())
    +    serverOpt.map(server => {
    +      server.close()
    +      server.join()
    +    })
    +    lock.lock()
    +    try {
    +      running = false
    +      blockingCondition.signalAll()
    +    } finally {
    +      lock.unlock()
    +    }
    +  }
    +
    +  override def configure(ctx: Context) {
    +    import SparkSinkConfig._
    +    hostname = ctx.getString(CONF_HOSTNAME, DEFAULT_HOSTNAME)
    +    val portOpt = Option(ctx.getInteger(CONF_PORT))
    +    if(portOpt.isDefined) {
    +      port = portOpt.get
    +    } else {
    +      throw new ConfigurationException("The Port to bind must be specified")
    +    }
    +    numProcessors = ctx.getInteger(PROCESSOR_COUNT, DEFAULT_PROCESSOR_COUNT)
    +    transactionTimeout = ctx.getInteger(CONF_TRANSACTION_TIMEOUT, DEFAULT_TRANSACTION_TIMEOUT)
    +    maxThreads = ctx.getInteger(CONF_MAX_THREADS, DEFAULT_MAX_THREADS)
    +  }
    +
    +  override def process(): Status = {
    +    // This method is called in a loop by the Flume framework - block it until the sink is
    +    // stopped to save CPU resources
    +    lock.lock()
    +    try {
    +      while(running) {
    +        blockingCondition.await()
    +      }
    +    } finally {
    +      lock.unlock()
    +    }
    +    Status.BACKOFF
    +  }
    +
    +
    +  // Object representing an empty batch returned by the txn processor due to some error.
    +  case object ErrorEventBatch extends EventBatch
    +
    +  private class AvroCallbackHandler() extends SparkFlumeProtocol {
    +
    +    override def getEventBatch(n: Int): EventBatch = {
    +      val processor = processorFactory.get.checkOut(n)
    +      transactionExecutorOpt.map(executor => executor.submit(processor))
    +      // Wait until a batch is available - can be null if some error was thrown
    +      val eventBatch = processor.eventQueue.take()
    +      eventBatch match {
    +        case ErrorEventBatch => throw new FlumeException("Something went wrong. No events" +
    +          " retrieved from channel.")
    +        case events => {
    +          processorMap.put(events.getSequenceNumber, processor)
    +          if (LOG.isDebugEnabled) {
    +            LOG.debug("Sent " + events.getEventBatch.size() +
    +              " events with sequence number: " + events.getSequenceNumber)
    +          }
    +          events
    +        }
    +      }
    +    }
    +
    +    override def ack(sequenceNumber: CharSequence): Void = {
    +      completeTransaction(sequenceNumber, success = true)
    +      null
    +    }
    +
    +    override def nack(sequenceNumber: CharSequence): Void = {
    +      completeTransaction(sequenceNumber, success = false)
    +      LOG.info("Spark failed to commit transaction. Will reattempt events.")
    +      null
    +    }
    +
    +    def completeTransaction(sequenceNumber: CharSequence, success: Boolean) {
    +      val processorOpt = Option(processorMap.remove(sequenceNumber))
    +      if (processorOpt.isDefined) {
    +        val processor = processorOpt.get
    +        processor.resultQueueUpdateLock.lock()
    +        try {
    +          // Is the sequence number the same as the one the processor is processing? If not,
    +          // don't update {
    +          if (processor.eventBatch.getSequenceNumber.equals(sequenceNumber)) {
    +            processor.resultQueue.put(success)
    +          }
    +        } finally {
    +          processor.resultQueueUpdateLock.unlock()
    +        }
    +      }
    +    }
    +  }
    +
    +  // Flume forces transactions to be thread-local (horrible, I know!)
    +  // So the sink basically spawns a new thread to pull the events out within a transaction.
    +  // The thread fills in the event batch object that is set before the thread is scheduled.
    +  // After filling it in, the thread waits on a condition - which is released only
    +  // when the success message comes back for the specific sequence number for that event batch.
    +  /**
    +   * This class represents a transaction on the Flume channel. This class runs a separate thread
    +   * which owns the transaction. It is blocked until the success call for that transaction comes
    +   * back.
    +   * @param maxBatchSize
    +   */
    +  private class TransactionProcessor(var maxBatchSize: Int) extends Callable[Void] {
    +    // Must be set to a new event batch before scheduling this!!
    +    val eventBatch = new EventBatch("", new util.LinkedList[SparkSinkEvent])
    +    val eventQueue = new SynchronousQueue[EventBatch]()
    +    val resultQueue = new SynchronousQueue[Boolean]()
    +    val resultQueueUpdateLock = new ReentrantLock()
    +
    +    object Zero {
    +      val zero = "0" // Oh, I miss static finals
    +    }
    +
    +
    +    override def call(): Void = {
    +      val tx = getChannel.getTransaction
    +      tx.begin()
    +      try {
    +        eventBatch.setSequenceNumber(seqBase + seqNum.incrementAndGet())
    +        val events = eventBatch.getEventBatch
    +        events.clear()
    +        val loop = new Breaks
    +        var gotEventsInThisTxn = false
    +        loop.breakable {
    +          var i = 0
    +          // Using for here causes the maxBatchSize change to be ineffective as the Range gets
    +          // pregenerated
    +          while (i < maxBatchSize) {
    +            i += 1
    +            val eventOpt = Option(getChannel.take())
    +            eventOpt.map(event => {
    +              events.add(new SparkSinkEvent(toCharSequenceMap(event
    +                .getHeaders),
    +                ByteBuffer.wrap(event.getBody)))
    +              gotEventsInThisTxn = true
    +            })
    +            if (eventOpt.isEmpty) {
    +              if (!gotEventsInThisTxn) {
    +                // To avoid sending empty batches, we wait till events are available backing off
    +                // between attempts to get events. Each attempt to get an event though causes one
    +                // iteration to be lost. To ensure that we still send back maxBatchSize number of
    +                // events, we cheat and increase the maxBatchSize by 1 to account for the lost
    +                // iteration. Even throwing an exception is expensive as Avro will serialize it
    +                // and send it over the wire, which is useless. Before incrementing though,
    +                // ensure that we are not anywhere near INT_MAX.
    +                if (maxBatchSize >= Int.MaxValue / 2) {
    +                  // Random sanity check
    +                  throw new RuntimeException("Safety exception - polled too many times, no events!")
    +                }
    +                maxBatchSize += 1
    +                Thread.sleep(500)
    +              } else {
    +                loop.break()
    +              }
    +            }
    +          }
    +        }
    +        // Make the data available to the sender thread
    +        eventQueue.put(eventBatch)
    +
    +        // Wait till timeout for the ack/nack
    +        val maybeResult = Option(resultQueue.poll(transactionTimeout, TimeUnit.SECONDS))
    +        // There is a race condition here.
    +        // 1. This times out.
    +        // 2. The result is empty, so timeout exception is thrown.
    +        // 3. The ack comes in before the finally block is entered
    +        // 4. The thread with the ack has a handle to this processor,
    +        // and another thread has the same processor checked out
    +        // (since the finally block was executed and the processor checked back in)
    +        // 5. The thread with the ack now updates the result queue,
    +        // so the processor thinks it is the ack for the current batch.
    +        // To avoid this - update the sequence number to "0" (with or without a result - does not
    +        // matter).
    +        // In the ack method, check if the seq number is the same as the processor's -
    +        // if they are then update the result queue. Now if the
    +        // processor updates the seq number first - the ack/nack never updates the result. If the
    +        // ack/nack updates the
    +        // result after the timeout but before the seq number is updated to "0" it does not
    +        // matter - the processor would
    +        // still timeout and the result is cleared before reusing the processor.
    +        // Unfortunately, this needs to be done from within a lock
    +        // to make sure that the new sequence number is actually visible to the ack thread
    +        // (happens-before)
    +        resultQueueUpdateLock.lock()
    +        try {
    --- End diff --
    
    Even I hope there is a cleaner way of doing this. Unfortunately, handling race conditions often does not have a clean way. In this case, the reason all this needs to be done is because of how Flume hides transactions as thread-local. 



---
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 infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] spark pull request: SPARK-1729. Make Flume pull data from source, ...

Posted by joyyoj <gi...@git.apache.org>.
Github user joyyoj commented on a diff in the pull request:

    https://github.com/apache/spark/pull/807#discussion_r13740438
  
    --- Diff: external/flume/src/main/scala/org/apache/spark/streaming/flume/EventTransformer.scala ---
    @@ -0,0 +1,72 @@
    +/*
    + * 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.streaming.flume
    +
    +import java.io.{ObjectOutput, ObjectInput}
    +
    +import scala.collection.JavaConversions._
    +
    +import org.apache.spark.util.Utils
    +import org.apache.spark.Logging
    +
    +/**
    + * A simple object that provides the implementation of readExternal and writeExternal for both
    + * the wrapper classes for Flume-style Events.
    + */
    +object EventTransformer extends Logging {
    +  def readExternal(in: ObjectInput): (java.util.HashMap[CharSequence, CharSequence],
    +    Array[Byte]) = {
    +    val bodyLength = in.readInt()
    +    val bodyBuff = new Array[Byte](bodyLength)
    +    in.read(bodyBuff)
    +
    +    val numHeaders = in.readInt()
    +    val headers = new java.util.HashMap[CharSequence, CharSequence]
    +
    +    for (i <- 0 until numHeaders) {
    +      val keyLength = in.readInt()
    +      val keyBuff = new Array[Byte](keyLength)
    +      in.read(keyBuff)
    +      val key: String = Utils.deserialize(keyBuff)
    +
    +      val valLength = in.readInt()
    +      val valBuff = new Array[Byte](valLength)
    +      in.read(valBuff)
    --- End diff --
    
    readFully


---
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 infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] spark pull request: SPARK-1729. Make Flume pull data from source, ...

Posted by tdas <gi...@git.apache.org>.
Github user tdas commented on a diff in the pull request:

    https://github.com/apache/spark/pull/807#discussion_r13465751
  
    --- Diff: external/flume-sink/src/main/scala/org/apache/spark/flume/sink/SparkSink.scala ---
    @@ -0,0 +1,392 @@
    +/*
    + * 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.flume.sink
    +
    +import org.apache.flume.sink.AbstractSink
    +import java.util.concurrent.locks.ReentrantLock
    +import org.apache.flume.Sink.Status
    +import org.apache.spark.flume.{SparkSinkEvent, EventBatch, SparkFlumeProtocol}
    +import scala.util.control.Breaks
    +import java.nio.ByteBuffer
    +import org.apache.flume.{FlumeException, Context}
    +import org.slf4j.LoggerFactory
    +import java.util.concurrent.atomic.AtomicLong
    +import org.apache.commons.lang.RandomStringUtils
    +import java.util.concurrent._
    +import java.util
    +import org.apache.flume.conf.{ConfigurationException, Configurable}
    +import com.google.common.util.concurrent.ThreadFactoryBuilder
    +import org.apache.avro.ipc.NettyServer
    +import org.apache.avro.ipc.specific.SpecificResponder
    +import java.net.InetSocketAddress
    +
    +class SparkSink() extends AbstractSink with Configurable {
    +  private val LOG = LoggerFactory.getLogger(this.getClass)
    +  private val lock = new ReentrantLock()
    +  private val blockingCondition = lock.newCondition()
    +
    +  // This sink will not persist sequence numbers and reuses them if it gets restarted.
    +  // So it is possible to commit a transaction which may have been meant for the sink before the
    +  // restart.
    +  // Since the new txn may not have the same sequence number we must guard against accidentally
    +  // committing
    +  // a new transaction. To reduce the probability of that happening a random string is prepended
    +  // to the sequence number.
    +  // Does not change for life of sink
    +  private val seqBase = RandomStringUtils.randomAlphanumeric(8)
    +  // Incremented for each transaction
    +  private val seqNum = new AtomicLong(0)
    +
    +  private var transactionExecutorOpt: Option[ExecutorService] = None
    +
    +  private var numProcessors: Integer = SparkSinkConfig.DEFAULT_PROCESSOR_COUNT
    +  private var transactionTimeout = SparkSinkConfig.DEFAULT_TRANSACTION_TIMEOUT
    +
    +  private val processorMap = new ConcurrentHashMap[CharSequence, TransactionProcessor]()
    +
    +  private var processorFactory: Option[SparkHandlerFactory] = None
    +  private var hostname: String = SparkSinkConfig.DEFAULT_HOSTNAME
    +  private var port: Int = 0
    +  private var maxThreads: Int = SparkSinkConfig.DEFAULT_MAX_THREADS
    +  private var serverOpt: Option[NettyServer] = None
    +  private var running = false
    +
    +  override def start() {
    +    transactionExecutorOpt = Option(Executors.newFixedThreadPool(numProcessors,
    +      new ThreadFactoryBuilder().setDaemon(true)
    +        .setNameFormat("Spark Sink, " + getName + " Processor Thread - %d").build()))
    +
    +    processorFactory = Option(new SparkHandlerFactory(numProcessors))
    +
    +    val responder = new SpecificResponder(classOf[SparkFlumeProtocol], new AvroCallbackHandler())
    +
    +    // Using the constructor that takes specific thread-pools requires bringing in netty
    +    // dependencies which are being excluded in the build. In practice,
    +    // Netty dependencies are already available on the JVM as Flume would have pulled them in.
    +    serverOpt = Option(new NettyServer(responder, new InetSocketAddress(hostname, port)))
    +
    +    serverOpt.map(server => server.start())
    +    lock.lock()
    +    try {
    +      running = true
    +    } finally {
    +      lock.unlock()
    +    }
    +    super.start()
    +  }
    +
    +  override def stop() {
    +    transactionExecutorOpt.map(executor => executor.shutdownNow())
    +    serverOpt.map(server => {
    +      server.close()
    +      server.join()
    +    })
    +    lock.lock()
    +    try {
    +      running = false
    +      blockingCondition.signalAll()
    +    } finally {
    +      lock.unlock()
    +    }
    +  }
    +
    +  override def configure(ctx: Context) {
    +    import SparkSinkConfig._
    +    hostname = ctx.getString(CONF_HOSTNAME, DEFAULT_HOSTNAME)
    +    val portOpt = Option(ctx.getInteger(CONF_PORT))
    +    if(portOpt.isDefined) {
    +      port = portOpt.get
    +    } else {
    +      throw new ConfigurationException("The Port to bind must be specified")
    +    }
    +    numProcessors = ctx.getInteger(PROCESSOR_COUNT, DEFAULT_PROCESSOR_COUNT)
    +    transactionTimeout = ctx.getInteger(CONF_TRANSACTION_TIMEOUT, DEFAULT_TRANSACTION_TIMEOUT)
    +    maxThreads = ctx.getInteger(CONF_MAX_THREADS, DEFAULT_MAX_THREADS)
    +  }
    +
    +  override def process(): Status = {
    +    // This method is called in a loop by the Flume framework - block it until the sink is
    +    // stopped to save CPU resources
    +    lock.lock()
    +    try {
    +      while(running) {
    +        blockingCondition.await()
    +      }
    +    } finally {
    +      lock.unlock()
    +    }
    +    Status.BACKOFF
    +  }
    +
    +
    +  // Object representing an empty batch returned by the txn processor due to some error.
    +  case object ErrorEventBatch extends EventBatch
    +
    +  private class AvroCallbackHandler() extends SparkFlumeProtocol {
    +
    +    override def getEventBatch(n: Int): EventBatch = {
    +      val processor = processorFactory.get.checkOut(n)
    +      transactionExecutorOpt.map(executor => executor.submit(processor))
    +      // Wait until a batch is available - can be null if some error was thrown
    +      val eventBatch = processor.eventQueue.take()
    +      eventBatch match {
    +        case ErrorEventBatch => throw new FlumeException("Something went wrong. No events" +
    +          " retrieved from channel.")
    +        case events => {
    +          processorMap.put(events.getSequenceNumber, processor)
    +          if (LOG.isDebugEnabled) {
    +            LOG.debug("Sent " + events.getEventBatch.size() +
    +              " events with sequence number: " + events.getSequenceNumber)
    +          }
    +          events
    +        }
    +      }
    +    }
    +
    +    override def ack(sequenceNumber: CharSequence): Void = {
    +      completeTransaction(sequenceNumber, success = true)
    +      null
    +    }
    +
    +    override def nack(sequenceNumber: CharSequence): Void = {
    +      completeTransaction(sequenceNumber, success = false)
    +      LOG.info("Spark failed to commit transaction. Will reattempt events.")
    +      null
    +    }
    +
    +    def completeTransaction(sequenceNumber: CharSequence, success: Boolean) {
    +      val processorOpt = Option(processorMap.remove(sequenceNumber))
    +      if (processorOpt.isDefined) {
    +        val processor = processorOpt.get
    +        processor.resultQueueUpdateLock.lock()
    +        try {
    +          // Is the sequence number the same as the one the processor is processing? If not,
    +          // don't update {
    +          if (processor.eventBatch.getSequenceNumber.equals(sequenceNumber)) {
    +            processor.resultQueue.put(success)
    +          }
    +        } finally {
    +          processor.resultQueueUpdateLock.unlock()
    +        }
    +      }
    +    }
    +  }
    +
    +  // Flume forces transactions to be thread-local (horrible, I know!)
    +  // So the sink basically spawns a new thread to pull the events out within a transaction.
    +  // The thread fills in the event batch object that is set before the thread is scheduled.
    +  // After filling it in, the thread waits on a condition - which is released only
    +  // when the success message comes back for the specific sequence number for that event batch.
    +  /**
    +   * This class represents a transaction on the Flume channel. This class runs a separate thread
    +   * which owns the transaction. It is blocked until the success call for that transaction comes
    +   * back.
    +   * @param maxBatchSize
    +   */
    +  private class TransactionProcessor(var maxBatchSize: Int) extends Callable[Void] {
    +    // Must be set to a new event batch before scheduling this!!
    +    val eventBatch = new EventBatch("", new util.LinkedList[SparkSinkEvent])
    +    val eventQueue = new SynchronousQueue[EventBatch]()
    +    val resultQueue = new SynchronousQueue[Boolean]()
    +    val resultQueueUpdateLock = new ReentrantLock()
    +
    +    object Zero {
    +      val zero = "0" // Oh, I miss static finals
    +    }
    +
    +
    +    override def call(): Void = {
    +      val tx = getChannel.getTransaction
    +      tx.begin()
    +      try {
    +        eventBatch.setSequenceNumber(seqBase + seqNum.incrementAndGet())
    +        val events = eventBatch.getEventBatch
    +        events.clear()
    +        val loop = new Breaks
    +        var gotEventsInThisTxn = false
    +        loop.breakable {
    +          var i = 0
    +          // Using for here causes the maxBatchSize change to be ineffective as the Range gets
    +          // pregenerated
    +          while (i < maxBatchSize) {
    +            i += 1
    +            val eventOpt = Option(getChannel.take())
    +            eventOpt.map(event => {
    +              events.add(new SparkSinkEvent(toCharSequenceMap(event
    +                .getHeaders),
    +                ByteBuffer.wrap(event.getBody)))
    +              gotEventsInThisTxn = true
    +            })
    +            if (eventOpt.isEmpty) {
    +              if (!gotEventsInThisTxn) {
    +                // To avoid sending empty batches, we wait till events are available backing off
    +                // between attempts to get events. Each attempt to get an event though causes one
    +                // iteration to be lost. To ensure that we still send back maxBatchSize number of
    +                // events, we cheat and increase the maxBatchSize by 1 to account for the lost
    +                // iteration. Even throwing an exception is expensive as Avro will serialize it
    +                // and send it over the wire, which is useless. Before incrementing though,
    +                // ensure that we are not anywhere near INT_MAX.
    +                if (maxBatchSize >= Int.MaxValue / 2) {
    +                  // Random sanity check
    +                  throw new RuntimeException("Safety exception - polled too many times, no events!")
    +                }
    +                maxBatchSize += 1
    +                Thread.sleep(500)
    +              } else {
    +                loop.break()
    +              }
    +            }
    +          }
    +        }
    +        // Make the data available to the sender thread
    +        eventQueue.put(eventBatch)
    +
    +        // Wait till timeout for the ack/nack
    +        val maybeResult = Option(resultQueue.poll(transactionTimeout, TimeUnit.SECONDS))
    +        // There is a race condition here.
    +        // 1. This times out.
    +        // 2. The result is empty, so timeout exception is thrown.
    +        // 3. The ack comes in before the finally block is entered
    +        // 4. The thread with the ack has a handle to this processor,
    +        // and another thread has the same processor checked out
    +        // (since the finally block was executed and the processor checked back in)
    +        // 5. The thread with the ack now updates the result queue,
    +        // so the processor thinks it is the ack for the current batch.
    +        // To avoid this - update the sequence number to "0" (with or without a result - does not
    +        // matter).
    +        // In the ack method, check if the seq number is the same as the processor's -
    +        // if they are then update the result queue. Now if the
    +        // processor updates the seq number first - the ack/nack never updates the result. If the
    +        // ack/nack updates the
    +        // result after the timeout but before the seq number is updated to "0" it does not
    +        // matter - the processor would
    +        // still timeout and the result is cleared before reusing the processor.
    +        // Unfortunately, this needs to be done from within a lock
    +        // to make sure that the new sequence number is actually visible to the ack thread
    +        // (happens-before)
    +        resultQueueUpdateLock.lock()
    +        try {
    +          eventBatch.setSequenceNumber(Zero.zero)
    +        } finally {
    +          resultQueueUpdateLock.unlock()
    +        }
    +        eventBatch.getEventBatch.clear()
    +        // If the batch failed on spark side, throw a FlumeException
    +        maybeResult.map(success =>
    +          if (!success) {
    +            throw new
    +                FlumeException("Spark could not accept events. The transaction will be retried.")
    +          }
    +        )
    +        // If the operation timed out, throw a TimeoutException
    +        if (maybeResult.isEmpty) {
    +          throw new TimeoutException("Spark did not respond within the timeout period of " +
    +            transactionTimeout + "seconds. Transaction will be retried")
    +        }
    +        null
    +      } catch {
    +        case e: Throwable =>
    +          try {
    +            LOG.warn("Error while attempting to remove events from the channel.", e)
    +            tx.rollback()
    +          } catch {
    +            case e1: Throwable => LOG.error(
    +              "Rollback failed while attempting to rollback due to commit failure.", e1)
    +          }
    +          null // No point rethrowing the exception
    +      } finally {
    +        // Must *always* release the caller thread
    +        eventQueue.put(ErrorEventBatch)
    +        // In the case of success coming after the timeout, but before resetting the seq number
    +        // remove the event from the map and then clear the value
    +        resultQueue.clear()
    +        processorMap.remove(eventBatch.getSequenceNumber)
    +        processorFactory.get.checkIn(this)
    +        tx.close()
    +      }
    +    }
    +
    +    def toCharSequenceMap(inMap: java.util.Map[String, String]): java.util.Map[CharSequence,
    +      CharSequence] = {
    +      val charSeqMap = new util.HashMap[CharSequence, CharSequence](inMap.size())
    +      charSeqMap.putAll(inMap)
    +      charSeqMap
    +    }
    +  }
    +
    +  private class SparkHandlerFactory(val maxInstances: Int) {
    +    val queue = new scala.collection.mutable.Queue[TransactionProcessor]
    +    val queueModificationLock = new ReentrantLock()
    +    var currentSize = 0
    +    val waitForCheckIn = queueModificationLock.newCondition()
    +
    +    def checkOut(n: Int): TransactionProcessor = {
    +      def getProcessor = {
    +        val processor = queue.dequeue()
    +        processor.maxBatchSize = n
    +        processor
    +      }
    +      queueModificationLock.lock()
    +      try {
    +        if (queue.size > 0) {
    +          getProcessor
    +        }
    +        else {
    +          if (currentSize < maxInstances) {
    +            currentSize += 1
    --- End diff --
    
    What is the intended logic here? What is `currentSize`? Is the current size of the queue (in which case, isnt `queue.size()` sufficient)? 


---
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 infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] spark pull request: SPARK-1729. Make Flume pull data from source, ...

Posted by pwendell <gi...@git.apache.org>.
Github user pwendell commented on a diff in the pull request:

    https://github.com/apache/spark/pull/807#discussion_r13825936
  
    --- Diff: external/flume/src/main/scala/org/apache/spark/streaming/flume/EventTransformer.scala ---
    @@ -0,0 +1,72 @@
    +/*
    + * 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.streaming.flume
    +
    +import java.io.{ObjectOutput, ObjectInput}
    +
    +import scala.collection.JavaConversions._
    +
    +import org.apache.spark.util.Utils
    +import org.apache.spark.Logging
    +
    +/**
    + * A simple object that provides the implementation of readExternal and writeExternal for both
    + * the wrapper classes for Flume-style Events.
    + */
    +object EventTransformer extends Logging {
    +  def readExternal(in: ObjectInput): (java.util.HashMap[CharSequence, CharSequence],
    +    Array[Byte]) = {
    +    val bodyLength = in.readInt()
    +    val bodyBuff = new Array[Byte](bodyLength)
    +    in.read(bodyBuff)
    +
    +    val numHeaders = in.readInt()
    +    val headers = new java.util.HashMap[CharSequence, CharSequence]
    +
    +    for (i <- 0 until numHeaders) {
    +      val keyLength = in.readInt()
    +      val keyBuff = new Array[Byte](keyLength)
    +      in.read(keyBuff)
    +      val key: String = Utils.deserialize(keyBuff)
    +
    +      val valLength = in.readInt()
    +      val valBuff = new Array[Byte](valLength)
    +      in.read(valBuff)
    --- End diff --
    
    https://github.com/apache/spark/blob/master/external/flume/src/main/scala/org/apache/spark/streaming/flume/FlumeInputDStream.scala#L79


---
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 infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] spark pull request: SPARK-1729. Make Flume pull data from source, ...

Posted by tdas <gi...@git.apache.org>.
Github user tdas commented on a diff in the pull request:

    https://github.com/apache/spark/pull/807#discussion_r13835028
  
    --- Diff: external/flume-sink/src/main/scala/org/apache/spark/flume/sink/SparkSink.scala ---
    @@ -0,0 +1,432 @@
    +/*
    + * 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.flume.sink
    +
    +import java.net.InetSocketAddress
    +import java.nio.ByteBuffer
    +import java.util
    +import java.util.concurrent._
    +import java.util.concurrent.atomic.AtomicLong
    +
    +import scala.util.control.Breaks
    +
    +import com.google.common.util.concurrent.ThreadFactoryBuilder
    +import org.apache.avro.ipc.NettyServer
    +import org.apache.avro.ipc.specific.SpecificResponder
    +import org.apache.commons.lang.RandomStringUtils
    +import org.apache.flume.Sink.Status
    +import org.apache.flume.conf.{ConfigurationException, Configurable}
    +import org.apache.flume.sink.AbstractSink
    +import org.apache.flume.{Channel, Transaction, FlumeException, Context}
    +import org.slf4j.LoggerFactory
    +
    +import org.apache.spark.flume.{SparkSinkEvent, EventBatch, SparkFlumeProtocol}
    +
    +/**
    + * A sink that uses Avro RPC to run a server that can be polled by Spark's
    + * FlumePollingInputDStream. This sink has the following configuration parameters:
    + *
    + * hostname - The hostname to bind to. Default: 0.0.0.0
    + * port - The port to bind to. (No default - mandatory)
    + * timeout - Time in seconds after which a transaction is rolled back,
    + * if an ACK is not received from Spark within that time
    + * threads - Number of threads to use to receive requests from Spark (Default: 10)
    + *
    + */
    +// Flume forces transactions to be thread-local. So each transaction *must* be committed, or
    +// rolled back from the thread it was originally created in. So each getEvents call from Spark
    +// creates a TransactionProcessor which runs in a new thread, in which the transaction is created
    +// and events are pulled off the channel. Once the events are sent to spark,
    +// that thread is blocked and the TransactionProcessor is saved in a map,
    +// until an ACK or NACK comes back or the transaction times out (after the specified timeout).
    +// When the response comes, the TransactionProcessor is retrieved and then unblocked,
    +// at which point the transaction is committed or rolled back.
    +class SparkSink extends AbstractSink with Configurable {
    --- End diff --
    
    Since these are separate classes, its probably better to split these into separate files.


---
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 infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] spark pull request: [STREAMING] SPARK-1729. Make Flume pull data f...

Posted by harishreedharan <gi...@git.apache.org>.
Github user harishreedharan commented on the pull request:

    https://github.com/apache/spark/pull/807#issuecomment-50394017
  
    Added sparkSink to mima excludes. This should fix the Jenkins failure.


---
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 infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] spark pull request: [STREAMING] SPARK-1729. Make Flume pull data f...

Posted by tdas <gi...@git.apache.org>.
Github user tdas commented on the pull request:

    https://github.com/apache/spark/pull/807#issuecomment-50378066
  
    Jenkins, this is ok to test.


---
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 infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] spark pull request: SPARK-1729. Make Flume pull data from source, ...

Posted by tdas <gi...@git.apache.org>.
Github user tdas commented on a diff in the pull request:

    https://github.com/apache/spark/pull/807#discussion_r13838881
  
    --- Diff: external/flume-sink/src/main/scala/org/apache/spark/flume/sink/SparkSink.scala ---
    @@ -0,0 +1,432 @@
    +/*
    + * 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.flume.sink
    +
    +import java.net.InetSocketAddress
    +import java.nio.ByteBuffer
    +import java.util
    +import java.util.concurrent._
    +import java.util.concurrent.atomic.AtomicLong
    +
    +import scala.util.control.Breaks
    +
    +import com.google.common.util.concurrent.ThreadFactoryBuilder
    +import org.apache.avro.ipc.NettyServer
    +import org.apache.avro.ipc.specific.SpecificResponder
    +import org.apache.commons.lang.RandomStringUtils
    +import org.apache.flume.Sink.Status
    +import org.apache.flume.conf.{ConfigurationException, Configurable}
    +import org.apache.flume.sink.AbstractSink
    +import org.apache.flume.{Channel, Transaction, FlumeException, Context}
    +import org.slf4j.LoggerFactory
    +
    +import org.apache.spark.flume.{SparkSinkEvent, EventBatch, SparkFlumeProtocol}
    +
    +/**
    + * A sink that uses Avro RPC to run a server that can be polled by Spark's
    + * FlumePollingInputDStream. This sink has the following configuration parameters:
    + *
    + * hostname - The hostname to bind to. Default: 0.0.0.0
    + * port - The port to bind to. (No default - mandatory)
    + * timeout - Time in seconds after which a transaction is rolled back,
    + * if an ACK is not received from Spark within that time
    + * threads - Number of threads to use to receive requests from Spark (Default: 10)
    + *
    + */
    +// Flume forces transactions to be thread-local. So each transaction *must* be committed, or
    +// rolled back from the thread it was originally created in. So each getEvents call from Spark
    +// creates a TransactionProcessor which runs in a new thread, in which the transaction is created
    +// and events are pulled off the channel. Once the events are sent to spark,
    +// that thread is blocked and the TransactionProcessor is saved in a map,
    +// until an ACK or NACK comes back or the transaction times out (after the specified timeout).
    +// When the response comes, the TransactionProcessor is retrieved and then unblocked,
    +// at which point the transaction is committed or rolled back.
    +class SparkSink extends AbstractSink with Configurable {
    +
    +  // Size of the pool to use for holding transaction processors.
    +  private var poolSize: Integer = SparkSinkConfig.DEFAULT_THREADS
    +
    +  // Timeout for each transaction. If spark does not respond in this much time,
    +  // rollback the transaction
    +  private var transactionTimeout = SparkSinkConfig.DEFAULT_TRANSACTION_TIMEOUT
    +
    +  // Address info to bind on
    +  private var hostname: String = SparkSinkConfig.DEFAULT_HOSTNAME
    +  private var port: Int = 0
    +
    +  // Handle to the server
    +  private var serverOpt: Option[NettyServer] = None
    +
    +  // The handler that handles the callback from Avro
    +  private var handler: Option[SparkAvroCallbackHandler] = None
    +
    +  // Latch that blocks off the Flume framework from wasting 1 thread.
    +  private val blockingLatch = new CountDownLatch(1)
    +
    +  override def start() {
    +    handler = Option(new SparkAvroCallbackHandler(poolSize, getChannel, transactionTimeout))
    +    val responder = new SpecificResponder(classOf[SparkFlumeProtocol], handler.get)
    +    // Using the constructor that takes specific thread-pools requires bringing in netty
    +    // dependencies which are being excluded in the build. In practice,
    +    // Netty dependencies are already available on the JVM as Flume would have pulled them in.
    +    serverOpt = Option(new NettyServer(responder, new InetSocketAddress(hostname, port)))
    +    serverOpt.map(server => {
    +      server.start()
    +    })
    +    super.start()
    +  }
    +
    +  override def stop() {
    +    handler.map(callbackHandler => {
    +      callbackHandler.shutdown()
    +    })
    +    serverOpt.map(server => {
    +      server.close()
    +      server.join()
    +    })
    +    blockingLatch.countDown()
    +    super.stop()
    +  }
    +
    +  /**
    +   * @param ctx
    +   */
    +  override def configure(ctx: Context) {
    +    import SparkSinkConfig._
    +    hostname = ctx.getString(CONF_HOSTNAME, DEFAULT_HOSTNAME)
    +    port = Option(ctx.getInteger(CONF_PORT)).
    +      getOrElse(throw new ConfigurationException("The port to bind to must be specified"))
    +    poolSize = ctx.getInteger(THREADS, DEFAULT_THREADS)
    +    transactionTimeout = ctx.getInteger(CONF_TRANSACTION_TIMEOUT, DEFAULT_TRANSACTION_TIMEOUT)
    +  }
    +
    +  override def process(): Status = {
    +    // This method is called in a loop by the Flume framework - block it until the sink is
    +    // stopped to save CPU resources. The sink runner will interrupt this thread when the sink is
    +    // being shut down.
    +    blockingLatch.await()
    +    Status.BACKOFF
    +  }
    +}
    +
    +/**
    + * Class that implements the SparkFlumeProtocol, that is used by the Avro Netty Server to process
    + * requests. Each getEvents, ack and nack call is forwarded to an instance of this class.
    + * @param threads Number of threads to use to process requests.
    + * @param channel The channel that the sink pulls events from
    + * @param transactionTimeout Timeout in millis after which the transaction if not acked by Spark
    + *                           is rolled back.
    + */
    +private class SparkAvroCallbackHandler(val threads: Int, val channel: Channel,
    +  val transactionTimeout: Int) extends SparkFlumeProtocol {
    +  private val LOG = LoggerFactory.getLogger(classOf[SparkAvroCallbackHandler])
    +  val transactionExecutorOpt = Option(Executors.newFixedThreadPool(threads,
    +    new ThreadFactoryBuilder().setDaemon(true)
    +      .setNameFormat("Spark Sink Processor Thread - %d").build()))
    +  private val processorMap = new ConcurrentHashMap[CharSequence, TransactionProcessor]()
    +  // This sink will not persist sequence numbers and reuses them if it gets restarted.
    +  // So it is possible to commit a transaction which may have been meant for the sink before the
    +  // restart.
    +  // Since the new txn may not have the same sequence number we must guard against accidentally
    +  // committing a new transaction. To reduce the probability of that happening a random string is
    +  // prepended to the sequence number. Does not change for life of sink
    +  private val seqBase = RandomStringUtils.randomAlphanumeric(8)
    +  private val seqCounter = new AtomicLong(0)
    +
    +  /**
    +   * Returns a bunch of events to Spark over Avro RPC.
    +   * @param n Maximum number of events to return in a batch
    +   * @return [[EventBatch]] instance that has a sequence number and an array of at most n events
    +   */
    +  override def getEventBatch(n: Int): EventBatch = {
    +    val sequenceNumber = seqBase + seqCounter.incrementAndGet()
    +    val processor = new TransactionProcessor(channel, sequenceNumber,
    +      n, transactionTimeout, this)
    +    transactionExecutorOpt.map(executor => {
    +      executor.submit(processor)
    +    })
    +    // Wait until a batch is available - can be null if some error was thrown
    +    processor.getEventBatch match {
    +      case ErrorEventBatch => throw new FlumeException("Something went wrong. No events" +
    +        " retrieved from channel.")
    +      case eventBatch: EventBatch =>
    +        processorMap.put(sequenceNumber, processor)
    +        if (LOG.isDebugEnabled()) {
    +          LOG.debug("Sent " + eventBatch.getEvents.size() +
    +            " events with sequence number: " + eventBatch.getSequenceNumber)
    +        }
    +        eventBatch
    +    }
    +  }
    +
    +  /**
    +   * Called by Spark to indicate successful commit of a batch
    +   * @param sequenceNumber The sequence number of the event batch that was successful
    +   */
    +  override def ack(sequenceNumber: CharSequence): Void = {
    +    completeTransaction(sequenceNumber, success = true)
    +    null
    +  }
    +
    +  /**
    +   * Called by Spark to indicate failed commit of a batch
    +   * @param sequenceNumber The sequence number of the event batch that failed
    +   * @return
    +   */
    +  override def nack(sequenceNumber: CharSequence): Void = {
    +    completeTransaction(sequenceNumber, success = false)
    +    LOG.info("Spark failed to commit transaction. Will reattempt events.")
    +    null
    +  }
    +
    +  /**
    +   * Helper method to commit or rollback a transaction.
    +   * @param sequenceNumber The sequence number of the batch that was completed
    +   * @param success Whether the batch was successful or not.
    +   */
    +  private def completeTransaction(sequenceNumber: CharSequence, success: Boolean) {
    +    Option(removeAndGetProcessor(sequenceNumber)).map(processor => {
    +      processor.batchProcessed(success)
    +    })
    +  }
    +
    +  /**
    +   * Helper method to remove the TxnProcessor for a Sequence Number. Can be used to avoid a leak.
    +   * @param sequenceNumber
    +   * @return The transaction processor for the corresponding batch. Note that this instance is no
    +   *         longer tracked and the caller is responsible for that txn processor.
    +   */
    +  private[flume] def removeAndGetProcessor(sequenceNumber: CharSequence): TransactionProcessor = {
    +    processorMap.remove(sequenceNumber.toString) // The toString is required!
    +  }
    +
    +  /**
    +   * Shuts down the executor used to process transactions.
    +   */
    +  def shutdown() {
    +    transactionExecutorOpt.map(executor => {
    +      executor.shutdownNow()
    +    })
    +  }
    +}
    +
    +/**
    + * Object representing an empty batch returned by the txn processor due to some error.
    + */
    +case object ErrorEventBatch extends EventBatch
    +
    +// Flume forces transactions to be thread-local (horrible, I know!)
    +// So the sink basically spawns a new thread to pull the events out within a transaction.
    +// The thread fills in the event batch object that is set before the thread is scheduled.
    +// After filling it in, the thread waits on a condition - which is released only
    +// when the success message comes back for the specific sequence number for that event batch.
    +/**
    + * This class represents a transaction on the Flume channel. This class runs a separate thread
    + * which owns the transaction. The thread is blocked until the success call for that transaction
    + * comes back with an ACK or NACK.
    + * @param channel The channel from which to pull events
    + * @param seqNum The sequence number to use for the transaction. Must be unique
    + * @param maxBatchSize The maximum number of events to process per batch
    + * @param transactionTimeout Time in seconds after which a transaction must be rolled back
    + *                           without waiting for an ACK from Spark
    + * @param parent The parent [[SparkAvroCallbackHandler]] instance, for reporting timeouts
    + */
    +private class TransactionProcessor(val channel: Channel, val seqNum: String,
    +  var maxBatchSize: Int, val transactionTimeout: Int,
    +  val parent: SparkAvroCallbackHandler) extends Callable[Void] {
    +
    +  private val LOG = LoggerFactory.getLogger(classOf[TransactionProcessor])
    +
    +  // If a real batch is not returned, we always have to return an error batch.
    +  @volatile private var eventBatch: EventBatch = ErrorEventBatch
    +
    +  // Synchronization primitives
    +  val batchGeneratedLatch = new CountDownLatch(1)
    +  val batchAckLatch = new CountDownLatch(1)
    +
    +  // Sanity check to ensure we don't loop like crazy
    +  val totalAttemptsToRemoveFromChannel = Int.MaxValue / 2
    +
    +  // OK to use volatile, since the change would only make this true (otherwise it will be
    +  // changed to false - we never apply a negation operation to this) - which means the transaction
    +  // succeeded.
    +  @volatile private var batchSuccess = false
    +
    +  // The transaction that this processor would handle
    +  var txOpt: Option[Transaction] = None
    +
    +  /**
    +   * Get an event batch from the channel. This method will block until a batch of events is
    +   * available from the channel. If no events are available after a large number of attempts of
    +   * polling the channel, this method will return [[ErrorEventBatch]].
    +   *
    +   * @return An [[EventBatch]] instance with sequence number set to [[seqNum]], filled with a
    +   *         maximum of [[maxBatchSize]] events
    +   */
    +  def getEventBatch: EventBatch = {
    +    batchGeneratedLatch.await()
    +    eventBatch
    +  }
    +
    +  /**
    +   * This method is to be called by the sink when it receives an ACK or NACK from Spark. This
    +   * method is a no-op if it is called after [[transactionTimeout]] has expired since
    +   * [[getEventBatch]] returned a batch of events.
    +   * @param success True if an ACK was received and the transaction should be committed, else false.
    +   */
    +  def batchProcessed(success: Boolean) {
    +    if (LOG.isDebugEnabled) {
    +      LOG.debug("Batch processed for sequence number: " + seqNum)
    +    }
    +    batchSuccess = success
    +    batchAckLatch.countDown()
    +  }
    +
    +  /**
    +   * Populates events into the event batch. If the batch cannot be populated,
    +   * this method will not set the event batch which will stay [[ErrorEventBatch]]
    +   */
    +  private def populateEvents() {
    +    try {
    +      txOpt = Option(channel.getTransaction)
    +      txOpt.map(tx => {
    +        tx.begin()
    +        val events = new util.ArrayList[SparkSinkEvent](maxBatchSize)
    +        val loop = new Breaks
    +        var gotEventsInThisTxn = false
    +        var loopCounter: Int = 0
    +        loop.breakable {
    +          while (events.size() < maxBatchSize
    +            && loopCounter < totalAttemptsToRemoveFromChannel) {
    +            loopCounter += 1
    +            Option(channel.take()) match {
    +              case Some(event) =>
    +                events.add(new SparkSinkEvent(toCharSequenceMap(event.getHeaders),
    +                  ByteBuffer.wrap(event.getBody)))
    +                gotEventsInThisTxn = true
    +              case None =>
    +                if (!gotEventsInThisTxn) {
    +                  TimeUnit.MILLISECONDS.sleep(500)
    +                } else {
    +                  loop.break()
    +                }
    +            }
    +          }
    +        }
    +        if (!gotEventsInThisTxn) {
    +          throw new FlumeException("Tried too many times, didn't get any events from the channel")
    +        }
    +        // At this point, the events are available, so fill them into the event batch
    +        eventBatch = new EventBatch(seqNum, events)
    +      })
    +    } catch {
    +      case e: Throwable =>
    +        LOG.error("Error while processing transaction.", e)
    +        try {
    +          txOpt.map(tx => {
    +            rollbackAndClose(tx, close = true)
    +          })
    +        } finally {
    +          // Avro might serialize the exception and cause a NACK,
    +          // so don't bother with the transaction
    +          txOpt = None
    +        }
    +    } finally {
    +      batchGeneratedLatch.countDown()
    +    }
    +  }
    +
    +  /**
    +   * Waits for upto [[transactionTimeout]] seconds for an ACK. If an ACK comes in,
    +   * this method commits the transaction with the channel. If the ACK does not come in within
    +   * that time or a NACK comes in, this method rolls back the transaction.
    +   */
    +  private def processAckOrNack() {
    +    batchAckLatch.await(transactionTimeout, TimeUnit.SECONDS)
    +    txOpt.map(tx => {
    +      if (batchSuccess) {
    +        try {
    +          tx.commit()
    +        } catch {
    +          case e: Throwable =>
    +            rollbackAndClose(tx, close = false) // tx will be closed later anyway
    --- End diff --
    
    The rollback logs it as a generic "rolling back" message; it does not log the reason behind the rollback in detail enough. From what I see, there are a number of cases when a rollback can occur
    - no data received
    - exception in receiving data
    - data received, sent to receiver, but nack received
    - data received, sent to receiver, but ack not received by timeout
    - data receiver, sent to receiver, exception will waiting for ack (may be same as above)
    
    We should be able to very easily identify which of the cases caused the rollback of the transaction. It need not require logging in the rollbackAndClose function, but at least all control paths leading to a failure of the transaction should get logged for easy debugging.



---
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 infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] spark pull request: SPARK-1729. Make Flume pull data from source, ...

Posted by harishreedharan <gi...@git.apache.org>.
Github user harishreedharan commented on a diff in the pull request:

    https://github.com/apache/spark/pull/807#discussion_r13471152
  
    --- Diff: external/flume-sink/src/main/scala/org/apache/spark/flume/sink/SparkSink.scala ---
    @@ -0,0 +1,392 @@
    +/*
    + * 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.flume.sink
    +
    +import org.apache.flume.sink.AbstractSink
    +import java.util.concurrent.locks.ReentrantLock
    +import org.apache.flume.Sink.Status
    +import org.apache.spark.flume.{SparkSinkEvent, EventBatch, SparkFlumeProtocol}
    +import scala.util.control.Breaks
    +import java.nio.ByteBuffer
    +import org.apache.flume.{FlumeException, Context}
    +import org.slf4j.LoggerFactory
    +import java.util.concurrent.atomic.AtomicLong
    +import org.apache.commons.lang.RandomStringUtils
    +import java.util.concurrent._
    +import java.util
    +import org.apache.flume.conf.{ConfigurationException, Configurable}
    +import com.google.common.util.concurrent.ThreadFactoryBuilder
    +import org.apache.avro.ipc.NettyServer
    +import org.apache.avro.ipc.specific.SpecificResponder
    +import java.net.InetSocketAddress
    +
    +class SparkSink() extends AbstractSink with Configurable {
    +  private val LOG = LoggerFactory.getLogger(this.getClass)
    +  private val lock = new ReentrantLock()
    +  private val blockingCondition = lock.newCondition()
    +
    +  // This sink will not persist sequence numbers and reuses them if it gets restarted.
    +  // So it is possible to commit a transaction which may have been meant for the sink before the
    +  // restart.
    +  // Since the new txn may not have the same sequence number we must guard against accidentally
    +  // committing
    +  // a new transaction. To reduce the probability of that happening a random string is prepended
    +  // to the sequence number.
    +  // Does not change for life of sink
    +  private val seqBase = RandomStringUtils.randomAlphanumeric(8)
    +  // Incremented for each transaction
    +  private val seqNum = new AtomicLong(0)
    +
    +  private var transactionExecutorOpt: Option[ExecutorService] = None
    +
    +  private var numProcessors: Integer = SparkSinkConfig.DEFAULT_PROCESSOR_COUNT
    +  private var transactionTimeout = SparkSinkConfig.DEFAULT_TRANSACTION_TIMEOUT
    +
    +  private val processorMap = new ConcurrentHashMap[CharSequence, TransactionProcessor]()
    +
    +  private var processorFactory: Option[SparkHandlerFactory] = None
    +  private var hostname: String = SparkSinkConfig.DEFAULT_HOSTNAME
    +  private var port: Int = 0
    +  private var maxThreads: Int = SparkSinkConfig.DEFAULT_MAX_THREADS
    +  private var serverOpt: Option[NettyServer] = None
    +  private var running = false
    +
    +  override def start() {
    +    transactionExecutorOpt = Option(Executors.newFixedThreadPool(numProcessors,
    +      new ThreadFactoryBuilder().setDaemon(true)
    +        .setNameFormat("Spark Sink, " + getName + " Processor Thread - %d").build()))
    +
    +    processorFactory = Option(new SparkHandlerFactory(numProcessors))
    +
    +    val responder = new SpecificResponder(classOf[SparkFlumeProtocol], new AvroCallbackHandler())
    +
    +    // Using the constructor that takes specific thread-pools requires bringing in netty
    +    // dependencies which are being excluded in the build. In practice,
    +    // Netty dependencies are already available on the JVM as Flume would have pulled them in.
    +    serverOpt = Option(new NettyServer(responder, new InetSocketAddress(hostname, port)))
    +
    +    serverOpt.map(server => server.start())
    +    lock.lock()
    +    try {
    +      running = true
    +    } finally {
    +      lock.unlock()
    +    }
    +    super.start()
    +  }
    +
    +  override def stop() {
    +    transactionExecutorOpt.map(executor => executor.shutdownNow())
    +    serverOpt.map(server => {
    +      server.close()
    +      server.join()
    +    })
    +    lock.lock()
    +    try {
    +      running = false
    +      blockingCondition.signalAll()
    +    } finally {
    +      lock.unlock()
    +    }
    +  }
    +
    +  override def configure(ctx: Context) {
    +    import SparkSinkConfig._
    +    hostname = ctx.getString(CONF_HOSTNAME, DEFAULT_HOSTNAME)
    +    val portOpt = Option(ctx.getInteger(CONF_PORT))
    +    if(portOpt.isDefined) {
    +      port = portOpt.get
    +    } else {
    +      throw new ConfigurationException("The Port to bind must be specified")
    +    }
    +    numProcessors = ctx.getInteger(PROCESSOR_COUNT, DEFAULT_PROCESSOR_COUNT)
    +    transactionTimeout = ctx.getInteger(CONF_TRANSACTION_TIMEOUT, DEFAULT_TRANSACTION_TIMEOUT)
    +    maxThreads = ctx.getInteger(CONF_MAX_THREADS, DEFAULT_MAX_THREADS)
    +  }
    +
    +  override def process(): Status = {
    +    // This method is called in a loop by the Flume framework - block it until the sink is
    +    // stopped to save CPU resources
    +    lock.lock()
    +    try {
    +      while(running) {
    +        blockingCondition.await()
    +      }
    +    } finally {
    +      lock.unlock()
    +    }
    +    Status.BACKOFF
    +  }
    +
    +
    +  // Object representing an empty batch returned by the txn processor due to some error.
    +  case object ErrorEventBatch extends EventBatch
    +
    +  private class AvroCallbackHandler() extends SparkFlumeProtocol {
    +
    +    override def getEventBatch(n: Int): EventBatch = {
    +      val processor = processorFactory.get.checkOut(n)
    +      transactionExecutorOpt.map(executor => executor.submit(processor))
    +      // Wait until a batch is available - can be null if some error was thrown
    +      val eventBatch = processor.eventQueue.take()
    +      eventBatch match {
    +        case ErrorEventBatch => throw new FlumeException("Something went wrong. No events" +
    +          " retrieved from channel.")
    +        case events => {
    +          processorMap.put(events.getSequenceNumber, processor)
    +          if (LOG.isDebugEnabled) {
    +            LOG.debug("Sent " + events.getEventBatch.size() +
    +              " events with sequence number: " + events.getSequenceNumber)
    +          }
    +          events
    +        }
    +      }
    +    }
    +
    +    override def ack(sequenceNumber: CharSequence): Void = {
    +      completeTransaction(sequenceNumber, success = true)
    +      null
    +    }
    +
    +    override def nack(sequenceNumber: CharSequence): Void = {
    +      completeTransaction(sequenceNumber, success = false)
    +      LOG.info("Spark failed to commit transaction. Will reattempt events.")
    +      null
    +    }
    +
    +    def completeTransaction(sequenceNumber: CharSequence, success: Boolean) {
    +      val processorOpt = Option(processorMap.remove(sequenceNumber))
    +      if (processorOpt.isDefined) {
    +        val processor = processorOpt.get
    +        processor.resultQueueUpdateLock.lock()
    +        try {
    +          // Is the sequence number the same as the one the processor is processing? If not,
    +          // don't update {
    +          if (processor.eventBatch.getSequenceNumber.equals(sequenceNumber)) {
    +            processor.resultQueue.put(success)
    +          }
    +        } finally {
    +          processor.resultQueueUpdateLock.unlock()
    +        }
    +      }
    +    }
    +  }
    +
    +  // Flume forces transactions to be thread-local (horrible, I know!)
    +  // So the sink basically spawns a new thread to pull the events out within a transaction.
    +  // The thread fills in the event batch object that is set before the thread is scheduled.
    +  // After filling it in, the thread waits on a condition - which is released only
    +  // when the success message comes back for the specific sequence number for that event batch.
    +  /**
    +   * This class represents a transaction on the Flume channel. This class runs a separate thread
    +   * which owns the transaction. It is blocked until the success call for that transaction comes
    +   * back.
    +   * @param maxBatchSize
    +   */
    +  private class TransactionProcessor(var maxBatchSize: Int) extends Callable[Void] {
    +    // Must be set to a new event batch before scheduling this!!
    +    val eventBatch = new EventBatch("", new util.LinkedList[SparkSinkEvent])
    +    val eventQueue = new SynchronousQueue[EventBatch]()
    +    val resultQueue = new SynchronousQueue[Boolean]()
    +    val resultQueueUpdateLock = new ReentrantLock()
    +
    +    object Zero {
    +      val zero = "0" // Oh, I miss static finals
    +    }
    +
    +
    +    override def call(): Void = {
    +      val tx = getChannel.getTransaction
    +      tx.begin()
    +      try {
    +        eventBatch.setSequenceNumber(seqBase + seqNum.incrementAndGet())
    +        val events = eventBatch.getEventBatch
    +        events.clear()
    +        val loop = new Breaks
    +        var gotEventsInThisTxn = false
    +        loop.breakable {
    +          var i = 0
    +          // Using for here causes the maxBatchSize change to be ineffective as the Range gets
    +          // pregenerated
    +          while (i < maxBatchSize) {
    +            i += 1
    +            val eventOpt = Option(getChannel.take())
    +            eventOpt.map(event => {
    +              events.add(new SparkSinkEvent(toCharSequenceMap(event
    +                .getHeaders),
    +                ByteBuffer.wrap(event.getBody)))
    +              gotEventsInThisTxn = true
    +            })
    +            if (eventOpt.isEmpty) {
    +              if (!gotEventsInThisTxn) {
    +                // To avoid sending empty batches, we wait till events are available backing off
    +                // between attempts to get events. Each attempt to get an event though causes one
    +                // iteration to be lost. To ensure that we still send back maxBatchSize number of
    +                // events, we cheat and increase the maxBatchSize by 1 to account for the lost
    +                // iteration. Even throwing an exception is expensive as Avro will serialize it
    +                // and send it over the wire, which is useless. Before incrementing though,
    +                // ensure that we are not anywhere near INT_MAX.
    +                if (maxBatchSize >= Int.MaxValue / 2) {
    +                  // Random sanity check
    +                  throw new RuntimeException("Safety exception - polled too many times, no events!")
    +                }
    +                maxBatchSize += 1
    +                Thread.sleep(500)
    +              } else {
    +                loop.break()
    +              }
    +            }
    +          }
    +        }
    +        // Make the data available to the sender thread
    +        eventQueue.put(eventBatch)
    +
    +        // Wait till timeout for the ack/nack
    +        val maybeResult = Option(resultQueue.poll(transactionTimeout, TimeUnit.SECONDS))
    +        // There is a race condition here.
    +        // 1. This times out.
    +        // 2. The result is empty, so timeout exception is thrown.
    +        // 3. The ack comes in before the finally block is entered
    +        // 4. The thread with the ack has a handle to this processor,
    +        // and another thread has the same processor checked out
    +        // (since the finally block was executed and the processor checked back in)
    +        // 5. The thread with the ack now updates the result queue,
    +        // so the processor thinks it is the ack for the current batch.
    +        // To avoid this - update the sequence number to "0" (with or without a result - does not
    +        // matter).
    +        // In the ack method, check if the seq number is the same as the processor's -
    +        // if they are then update the result queue. Now if the
    +        // processor updates the seq number first - the ack/nack never updates the result. If the
    +        // ack/nack updates the
    +        // result after the timeout but before the seq number is updated to "0" it does not
    +        // matter - the processor would
    +        // still timeout and the result is cleared before reusing the processor.
    +        // Unfortunately, this needs to be done from within a lock
    +        // to make sure that the new sequence number is actually visible to the ack thread
    +        // (happens-before)
    +        resultQueueUpdateLock.lock()
    +        try {
    +          eventBatch.setSequenceNumber(Zero.zero)
    +        } finally {
    +          resultQueueUpdateLock.unlock()
    +        }
    +        eventBatch.getEventBatch.clear()
    +        // If the batch failed on spark side, throw a FlumeException
    +        maybeResult.map(success =>
    +          if (!success) {
    +            throw new
    +                FlumeException("Spark could not accept events. The transaction will be retried.")
    +          }
    +        )
    +        // If the operation timed out, throw a TimeoutException
    +        if (maybeResult.isEmpty) {
    +          throw new TimeoutException("Spark did not respond within the timeout period of " +
    +            transactionTimeout + "seconds. Transaction will be retried")
    +        }
    +        null
    +      } catch {
    +        case e: Throwable =>
    +          try {
    +            LOG.warn("Error while attempting to remove events from the channel.", e)
    +            tx.rollback()
    +          } catch {
    +            case e1: Throwable => LOG.error(
    +              "Rollback failed while attempting to rollback due to commit failure.", e1)
    +          }
    +          null // No point rethrowing the exception
    +      } finally {
    +        // Must *always* release the caller thread
    +        eventQueue.put(ErrorEventBatch)
    +        // In the case of success coming after the timeout, but before resetting the seq number
    +        // remove the event from the map and then clear the value
    +        resultQueue.clear()
    +        processorMap.remove(eventBatch.getSequenceNumber)
    +        processorFactory.get.checkIn(this)
    +        tx.close()
    +      }
    +    }
    +
    +    def toCharSequenceMap(inMap: java.util.Map[String, String]): java.util.Map[CharSequence,
    +      CharSequence] = {
    +      val charSeqMap = new util.HashMap[CharSequence, CharSequence](inMap.size())
    +      charSeqMap.putAll(inMap)
    +      charSeqMap
    +    }
    +  }
    +
    +  private class SparkHandlerFactory(val maxInstances: Int) {
    +    val queue = new scala.collection.mutable.Queue[TransactionProcessor]
    +    val queueModificationLock = new ReentrantLock()
    +    var currentSize = 0
    +    val waitForCheckIn = queueModificationLock.newCondition()
    +
    +    def checkOut(n: Int): TransactionProcessor = {
    +      def getProcessor = {
    +        val processor = queue.dequeue()
    +        processor.maxBatchSize = n
    +        processor
    +      }
    +      queueModificationLock.lock()
    +      try {
    +        if (queue.size > 0) {
    +          getProcessor
    +        }
    +        else {
    +          if (currentSize < maxInstances) {
    +            currentSize += 1
    +            new TransactionProcessor(n)
    +          } else {
    +            // No events in queue and cannot initialize more!
    +            // Since currentSize never reduces, queue size increasing is the only hope
    +            while (queue.size == 0 && currentSize >= maxInstances) {
    +              waitForCheckIn.await()
    +            }
    +            getProcessor
    +          }
    +        }
    +      } finally {
    +        queueModificationLock.unlock()
    +      }
    +    }
    +
    +    def checkIn(processor: TransactionProcessor) {
    +      queueModificationLock.lock()
    --- End diff --
    
    Hmm, let me think about how we can get rid of the lock - since we are initializing processors lazily, we want to ensure that total still does not go over maxInstances.


---
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 infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] spark pull request: SPARK-1729. Make Flume pull data from source, ...

Posted by harishreedharan <gi...@git.apache.org>.
Github user harishreedharan commented on a diff in the pull request:

    https://github.com/apache/spark/pull/807#discussion_r13477267
  
    --- Diff: external/flume-sink/src/main/scala/org/apache/spark/flume/sink/SparkSink.scala ---
    @@ -0,0 +1,392 @@
    +/*
    + * 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.flume.sink
    +
    +import org.apache.flume.sink.AbstractSink
    +import java.util.concurrent.locks.ReentrantLock
    +import org.apache.flume.Sink.Status
    +import org.apache.spark.flume.{SparkSinkEvent, EventBatch, SparkFlumeProtocol}
    +import scala.util.control.Breaks
    +import java.nio.ByteBuffer
    +import org.apache.flume.{FlumeException, Context}
    +import org.slf4j.LoggerFactory
    +import java.util.concurrent.atomic.AtomicLong
    +import org.apache.commons.lang.RandomStringUtils
    +import java.util.concurrent._
    +import java.util
    +import org.apache.flume.conf.{ConfigurationException, Configurable}
    +import com.google.common.util.concurrent.ThreadFactoryBuilder
    +import org.apache.avro.ipc.NettyServer
    +import org.apache.avro.ipc.specific.SpecificResponder
    +import java.net.InetSocketAddress
    +
    +class SparkSink() extends AbstractSink with Configurable {
    +  private val LOG = LoggerFactory.getLogger(this.getClass)
    +  private val lock = new ReentrantLock()
    +  private val blockingCondition = lock.newCondition()
    +
    +  // This sink will not persist sequence numbers and reuses them if it gets restarted.
    +  // So it is possible to commit a transaction which may have been meant for the sink before the
    +  // restart.
    +  // Since the new txn may not have the same sequence number we must guard against accidentally
    +  // committing
    +  // a new transaction. To reduce the probability of that happening a random string is prepended
    +  // to the sequence number.
    +  // Does not change for life of sink
    +  private val seqBase = RandomStringUtils.randomAlphanumeric(8)
    +  // Incremented for each transaction
    +  private val seqNum = new AtomicLong(0)
    +
    +  private var transactionExecutorOpt: Option[ExecutorService] = None
    +
    +  private var numProcessors: Integer = SparkSinkConfig.DEFAULT_PROCESSOR_COUNT
    +  private var transactionTimeout = SparkSinkConfig.DEFAULT_TRANSACTION_TIMEOUT
    +
    +  private val processorMap = new ConcurrentHashMap[CharSequence, TransactionProcessor]()
    +
    +  private var processorFactory: Option[SparkHandlerFactory] = None
    +  private var hostname: String = SparkSinkConfig.DEFAULT_HOSTNAME
    +  private var port: Int = 0
    +  private var maxThreads: Int = SparkSinkConfig.DEFAULT_MAX_THREADS
    +  private var serverOpt: Option[NettyServer] = None
    +  private var running = false
    +
    +  override def start() {
    +    transactionExecutorOpt = Option(Executors.newFixedThreadPool(numProcessors,
    +      new ThreadFactoryBuilder().setDaemon(true)
    +        .setNameFormat("Spark Sink, " + getName + " Processor Thread - %d").build()))
    +
    +    processorFactory = Option(new SparkHandlerFactory(numProcessors))
    +
    +    val responder = new SpecificResponder(classOf[SparkFlumeProtocol], new AvroCallbackHandler())
    +
    +    // Using the constructor that takes specific thread-pools requires bringing in netty
    +    // dependencies which are being excluded in the build. In practice,
    +    // Netty dependencies are already available on the JVM as Flume would have pulled them in.
    +    serverOpt = Option(new NettyServer(responder, new InetSocketAddress(hostname, port)))
    +
    +    serverOpt.map(server => server.start())
    +    lock.lock()
    +    try {
    +      running = true
    +    } finally {
    +      lock.unlock()
    +    }
    +    super.start()
    +  }
    +
    +  override def stop() {
    --- End diff --
    
    No, they will not be called concurrently.


---
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 infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] spark pull request: SPARK-1729. Make Flume pull data from source, ...

Posted by tdas <gi...@git.apache.org>.
Github user tdas commented on a diff in the pull request:

    https://github.com/apache/spark/pull/807#discussion_r13419975
  
    --- Diff: external/flume-sink/src/main/scala/org/apache/spark/flume/sink/SparkSink.scala ---
    @@ -0,0 +1,392 @@
    +/*
    + * 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.flume.sink
    +
    +import org.apache.flume.sink.AbstractSink
    --- End diff --
    
    https://cwiki.apache.org/confluence/display/SPARK/Spark+Code+Style+Guide#SparkCodeStyleGuide-Imports


---
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 infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] spark pull request: SPARK-1729. Make Flume pull data from source, ...

Posted by tdas <gi...@git.apache.org>.
Github user tdas commented on a diff in the pull request:

    https://github.com/apache/spark/pull/807#discussion_r13838530
  
    --- Diff: external/flume/src/main/scala/org/apache/spark/streaming/flume/FlumePollingInputDStream.scala ---
    @@ -0,0 +1,189 @@
    +/*
    + * 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.streaming.flume
    +
    +
    +import java.io.{ObjectOutput, ObjectInput, Externalizable}
    +import java.net.InetSocketAddress
    +import java.nio.ByteBuffer
    +import java.util.concurrent.{TimeUnit, Executors}
    +
    +import scala.collection.JavaConversions._
    +import scala.reflect.ClassTag
    +
    +import com.google.common.util.concurrent.ThreadFactoryBuilder
    +import org.apache.avro.ipc.NettyTransceiver
    +import org.apache.avro.ipc.specific.SpecificRequestor
    +import org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory
    +
    +import org.apache.spark.Logging
    +import org.apache.spark.flume.{SparkSinkEvent, SparkFlumeProtocol}
    +import org.apache.spark.storage.StorageLevel
    +import org.apache.spark.streaming.StreamingContext
    +import org.apache.spark.streaming.dstream.ReceiverInputDStream
    +import org.apache.spark.streaming.receiver.Receiver
    +
    +/**
    + * A [[ReceiverInputDStream]] that can be used to read data from several Flume agents running
    + * [[org.apache.spark.flume.sink.SparkSink]]s.
    + * @param ssc_ Streaming context that will execute this input stream
    + * @param addresses List of addresses at which SparkSinks are listening
    + * @param maxBatchSize Maximum size of a batch
    + * @param parallelism Number of parallel connections to open
    + * @param storageLevel The storage level to use.
    + * @tparam T Class type of the object of this stream
    + */
    +class FlumePollingInputDStream[T: ClassTag](
    +  @transient ssc_ : StreamingContext,
    +  val addresses: Seq[InetSocketAddress],
    +  val maxBatchSize: Int,
    +  val parallelism: Int,
    +  storageLevel: StorageLevel
    +) extends ReceiverInputDStream[SparkFlumePollingEvent](ssc_) {
    +  /**
    +   * Gets the receiver object that will be sent to the worker nodes
    +   * to receive data. This method needs to defined by any specific implementation
    +   * of a NetworkInputDStream.
    +   */
    +  override def getReceiver(): Receiver[SparkFlumePollingEvent] = {
    +    new FlumePollingReceiver(addresses, maxBatchSize, parallelism, storageLevel)
    +  }
    +}
    +
    +private[streaming] class FlumePollingReceiver(
    +  addresses: Seq[InetSocketAddress],
    +  maxBatchSize: Int,
    +  parallelism: Int,
    +  storageLevel: StorageLevel
    +) extends Receiver[SparkFlumePollingEvent](storageLevel) with Logging {
    +
    +  lazy val channelFactoryExecutor =
    +    Executors.newCachedThreadPool(new ThreadFactoryBuilder().setDaemon(true).
    +      setNameFormat("Flume Receiver Channel Thread - %d").build())
    +
    +  lazy val channelFactory =
    +    new NioClientSocketChannelFactory(channelFactoryExecutor, channelFactoryExecutor)
    +
    +  lazy val receiverExecutor = Executors.newFixedThreadPool(parallelism,
    +    new ThreadFactoryBuilder().setDaemon(true).setNameFormat("Flume Receiver Thread - %d").build())
    +
    +  private var connections = Array.empty[FlumeConnection] // temporarily empty, filled in later
    +
    +  override def onStart(): Unit = {
    +    // Create the connections to each Flume agent.
    +    connections = addresses.map(host => {
    +      val transceiver = new NettyTransceiver(host, channelFactory)
    +      val client = SpecificRequestor.getClient(classOf[SparkFlumeProtocol.Callback], transceiver)
    +      new FlumeConnection(transceiver, client)
    +    }).toArray
    +
    +    // Threads that pull data from Flume.
    +    val dataReceiver = new Runnable {
    +      override def run(): Unit = {
    +        var counter = 0
    +        while (true) {
    +          counter = counter % connections.size
    +          val client = connections(counter).client
    +          counter += 1
    +          val batch = client.getEventBatch(maxBatchSize)
    +          val seq = batch.getSequenceNumber
    +          val events: java.util.List[SparkSinkEvent] = batch.getEvents
    +          logDebug("Received batch of " + events.size() + " events with sequence number: " + seq)
    +          try {
    +            // Convert each Flume event to a serializable SparkPollingEvent
    +            events.foreach(event => {
    +              store(SparkFlumePollingEvent.fromSparkSinkEvent(event))
    +            })
    +            // Send an ack to Flume so that Flume discards the events from its channels.
    +            client.ack(seq)
    +          } catch {
    +            case e: Throwable =>
    +              try {
    --- End diff --
    
    same here, catch only exceptions.


---
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 infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] spark pull request: SPARK-1729. Make Flume pull data from source, ...

Posted by harishreedharan <gi...@git.apache.org>.
Github user harishreedharan commented on a diff in the pull request:

    https://github.com/apache/spark/pull/807#discussion_r13838182
  
    --- Diff: external/flume-sink/src/main/scala/org/apache/spark/flume/sink/SparkSink.scala ---
    @@ -0,0 +1,432 @@
    +/*
    + * 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.flume.sink
    +
    +import java.net.InetSocketAddress
    +import java.nio.ByteBuffer
    +import java.util
    +import java.util.concurrent._
    +import java.util.concurrent.atomic.AtomicLong
    +
    +import scala.util.control.Breaks
    +
    +import com.google.common.util.concurrent.ThreadFactoryBuilder
    +import org.apache.avro.ipc.NettyServer
    +import org.apache.avro.ipc.specific.SpecificResponder
    +import org.apache.commons.lang.RandomStringUtils
    +import org.apache.flume.Sink.Status
    +import org.apache.flume.conf.{ConfigurationException, Configurable}
    +import org.apache.flume.sink.AbstractSink
    +import org.apache.flume.{Channel, Transaction, FlumeException, Context}
    +import org.slf4j.LoggerFactory
    +
    +import org.apache.spark.flume.{SparkSinkEvent, EventBatch, SparkFlumeProtocol}
    +
    +/**
    + * A sink that uses Avro RPC to run a server that can be polled by Spark's
    + * FlumePollingInputDStream. This sink has the following configuration parameters:
    + *
    + * hostname - The hostname to bind to. Default: 0.0.0.0
    + * port - The port to bind to. (No default - mandatory)
    + * timeout - Time in seconds after which a transaction is rolled back,
    + * if an ACK is not received from Spark within that time
    + * threads - Number of threads to use to receive requests from Spark (Default: 10)
    + *
    + */
    +// Flume forces transactions to be thread-local. So each transaction *must* be committed, or
    +// rolled back from the thread it was originally created in. So each getEvents call from Spark
    +// creates a TransactionProcessor which runs in a new thread, in which the transaction is created
    +// and events are pulled off the channel. Once the events are sent to spark,
    +// that thread is blocked and the TransactionProcessor is saved in a map,
    +// until an ACK or NACK comes back or the transaction times out (after the specified timeout).
    +// When the response comes, the TransactionProcessor is retrieved and then unblocked,
    +// at which point the transaction is committed or rolled back.
    +class SparkSink extends AbstractSink with Configurable {
    +
    +  // Size of the pool to use for holding transaction processors.
    +  private var poolSize: Integer = SparkSinkConfig.DEFAULT_THREADS
    +
    +  // Timeout for each transaction. If spark does not respond in this much time,
    +  // rollback the transaction
    +  private var transactionTimeout = SparkSinkConfig.DEFAULT_TRANSACTION_TIMEOUT
    +
    +  // Address info to bind on
    +  private var hostname: String = SparkSinkConfig.DEFAULT_HOSTNAME
    +  private var port: Int = 0
    +
    +  // Handle to the server
    +  private var serverOpt: Option[NettyServer] = None
    +
    +  // The handler that handles the callback from Avro
    +  private var handler: Option[SparkAvroCallbackHandler] = None
    +
    +  // Latch that blocks off the Flume framework from wasting 1 thread.
    +  private val blockingLatch = new CountDownLatch(1)
    +
    +  override def start() {
    +    handler = Option(new SparkAvroCallbackHandler(poolSize, getChannel, transactionTimeout))
    +    val responder = new SpecificResponder(classOf[SparkFlumeProtocol], handler.get)
    +    // Using the constructor that takes specific thread-pools requires bringing in netty
    +    // dependencies which are being excluded in the build. In practice,
    +    // Netty dependencies are already available on the JVM as Flume would have pulled them in.
    +    serverOpt = Option(new NettyServer(responder, new InetSocketAddress(hostname, port)))
    +    serverOpt.map(server => {
    +      server.start()
    +    })
    +    super.start()
    +  }
    +
    +  override def stop() {
    +    handler.map(callbackHandler => {
    +      callbackHandler.shutdown()
    +    })
    +    serverOpt.map(server => {
    +      server.close()
    +      server.join()
    +    })
    +    blockingLatch.countDown()
    +    super.stop()
    +  }
    +
    +  /**
    +   * @param ctx
    +   */
    +  override def configure(ctx: Context) {
    +    import SparkSinkConfig._
    +    hostname = ctx.getString(CONF_HOSTNAME, DEFAULT_HOSTNAME)
    +    port = Option(ctx.getInteger(CONF_PORT)).
    +      getOrElse(throw new ConfigurationException("The port to bind to must be specified"))
    +    poolSize = ctx.getInteger(THREADS, DEFAULT_THREADS)
    +    transactionTimeout = ctx.getInteger(CONF_TRANSACTION_TIMEOUT, DEFAULT_TRANSACTION_TIMEOUT)
    +  }
    +
    +  override def process(): Status = {
    +    // This method is called in a loop by the Flume framework - block it until the sink is
    +    // stopped to save CPU resources. The sink runner will interrupt this thread when the sink is
    +    // being shut down.
    +    blockingLatch.await()
    +    Status.BACKOFF
    +  }
    +}
    +
    +/**
    + * Class that implements the SparkFlumeProtocol, that is used by the Avro Netty Server to process
    + * requests. Each getEvents, ack and nack call is forwarded to an instance of this class.
    + * @param threads Number of threads to use to process requests.
    + * @param channel The channel that the sink pulls events from
    + * @param transactionTimeout Timeout in millis after which the transaction if not acked by Spark
    + *                           is rolled back.
    + */
    +private class SparkAvroCallbackHandler(val threads: Int, val channel: Channel,
    +  val transactionTimeout: Int) extends SparkFlumeProtocol {
    +  private val LOG = LoggerFactory.getLogger(classOf[SparkAvroCallbackHandler])
    +  val transactionExecutorOpt = Option(Executors.newFixedThreadPool(threads,
    +    new ThreadFactoryBuilder().setDaemon(true)
    +      .setNameFormat("Spark Sink Processor Thread - %d").build()))
    +  private val processorMap = new ConcurrentHashMap[CharSequence, TransactionProcessor]()
    +  // This sink will not persist sequence numbers and reuses them if it gets restarted.
    +  // So it is possible to commit a transaction which may have been meant for the sink before the
    +  // restart.
    +  // Since the new txn may not have the same sequence number we must guard against accidentally
    +  // committing a new transaction. To reduce the probability of that happening a random string is
    +  // prepended to the sequence number. Does not change for life of sink
    +  private val seqBase = RandomStringUtils.randomAlphanumeric(8)
    +  private val seqCounter = new AtomicLong(0)
    +
    +  /**
    +   * Returns a bunch of events to Spark over Avro RPC.
    +   * @param n Maximum number of events to return in a batch
    +   * @return [[EventBatch]] instance that has a sequence number and an array of at most n events
    +   */
    +  override def getEventBatch(n: Int): EventBatch = {
    +    val sequenceNumber = seqBase + seqCounter.incrementAndGet()
    +    val processor = new TransactionProcessor(channel, sequenceNumber,
    +      n, transactionTimeout, this)
    +    transactionExecutorOpt.map(executor => {
    +      executor.submit(processor)
    +    })
    +    // Wait until a batch is available - can be null if some error was thrown
    +    processor.getEventBatch match {
    +      case ErrorEventBatch => throw new FlumeException("Something went wrong. No events" +
    +        " retrieved from channel.")
    +      case eventBatch: EventBatch =>
    +        processorMap.put(sequenceNumber, processor)
    +        if (LOG.isDebugEnabled()) {
    +          LOG.debug("Sent " + eventBatch.getEvents.size() +
    +            " events with sequence number: " + eventBatch.getSequenceNumber)
    +        }
    +        eventBatch
    +    }
    +  }
    +
    +  /**
    +   * Called by Spark to indicate successful commit of a batch
    +   * @param sequenceNumber The sequence number of the event batch that was successful
    +   */
    +  override def ack(sequenceNumber: CharSequence): Void = {
    +    completeTransaction(sequenceNumber, success = true)
    +    null
    +  }
    +
    +  /**
    +   * Called by Spark to indicate failed commit of a batch
    +   * @param sequenceNumber The sequence number of the event batch that failed
    +   * @return
    +   */
    +  override def nack(sequenceNumber: CharSequence): Void = {
    +    completeTransaction(sequenceNumber, success = false)
    +    LOG.info("Spark failed to commit transaction. Will reattempt events.")
    +    null
    +  }
    +
    +  /**
    +   * Helper method to commit or rollback a transaction.
    +   * @param sequenceNumber The sequence number of the batch that was completed
    +   * @param success Whether the batch was successful or not.
    +   */
    +  private def completeTransaction(sequenceNumber: CharSequence, success: Boolean) {
    +    Option(removeAndGetProcessor(sequenceNumber)).map(processor => {
    +      processor.batchProcessed(success)
    +    })
    +  }
    +
    +  /**
    +   * Helper method to remove the TxnProcessor for a Sequence Number. Can be used to avoid a leak.
    +   * @param sequenceNumber
    +   * @return The transaction processor for the corresponding batch. Note that this instance is no
    +   *         longer tracked and the caller is responsible for that txn processor.
    +   */
    +  private[flume] def removeAndGetProcessor(sequenceNumber: CharSequence): TransactionProcessor = {
    +    processorMap.remove(sequenceNumber.toString) // The toString is required!
    +  }
    +
    +  /**
    +   * Shuts down the executor used to process transactions.
    +   */
    +  def shutdown() {
    +    transactionExecutorOpt.map(executor => {
    +      executor.shutdownNow()
    +    })
    +  }
    +}
    +
    +/**
    + * Object representing an empty batch returned by the txn processor due to some error.
    + */
    +case object ErrorEventBatch extends EventBatch
    +
    +// Flume forces transactions to be thread-local (horrible, I know!)
    +// So the sink basically spawns a new thread to pull the events out within a transaction.
    +// The thread fills in the event batch object that is set before the thread is scheduled.
    +// After filling it in, the thread waits on a condition - which is released only
    +// when the success message comes back for the specific sequence number for that event batch.
    +/**
    + * This class represents a transaction on the Flume channel. This class runs a separate thread
    + * which owns the transaction. The thread is blocked until the success call for that transaction
    + * comes back with an ACK or NACK.
    + * @param channel The channel from which to pull events
    + * @param seqNum The sequence number to use for the transaction. Must be unique
    + * @param maxBatchSize The maximum number of events to process per batch
    + * @param transactionTimeout Time in seconds after which a transaction must be rolled back
    + *                           without waiting for an ACK from Spark
    + * @param parent The parent [[SparkAvroCallbackHandler]] instance, for reporting timeouts
    + */
    +private class TransactionProcessor(val channel: Channel, val seqNum: String,
    +  var maxBatchSize: Int, val transactionTimeout: Int,
    +  val parent: SparkAvroCallbackHandler) extends Callable[Void] {
    +
    +  private val LOG = LoggerFactory.getLogger(classOf[TransactionProcessor])
    +
    +  // If a real batch is not returned, we always have to return an error batch.
    +  @volatile private var eventBatch: EventBatch = ErrorEventBatch
    +
    +  // Synchronization primitives
    +  val batchGeneratedLatch = new CountDownLatch(1)
    +  val batchAckLatch = new CountDownLatch(1)
    +
    +  // Sanity check to ensure we don't loop like crazy
    +  val totalAttemptsToRemoveFromChannel = Int.MaxValue / 2
    +
    +  // OK to use volatile, since the change would only make this true (otherwise it will be
    +  // changed to false - we never apply a negation operation to this) - which means the transaction
    +  // succeeded.
    +  @volatile private var batchSuccess = false
    +
    +  // The transaction that this processor would handle
    +  var txOpt: Option[Transaction] = None
    +
    +  /**
    +   * Get an event batch from the channel. This method will block until a batch of events is
    +   * available from the channel. If no events are available after a large number of attempts of
    +   * polling the channel, this method will return [[ErrorEventBatch]].
    +   *
    +   * @return An [[EventBatch]] instance with sequence number set to [[seqNum]], filled with a
    +   *         maximum of [[maxBatchSize]] events
    +   */
    +  def getEventBatch: EventBatch = {
    +    batchGeneratedLatch.await()
    +    eventBatch
    +  }
    +
    +  /**
    +   * This method is to be called by the sink when it receives an ACK or NACK from Spark. This
    +   * method is a no-op if it is called after [[transactionTimeout]] has expired since
    +   * [[getEventBatch]] returned a batch of events.
    +   * @param success True if an ACK was received and the transaction should be committed, else false.
    +   */
    +  def batchProcessed(success: Boolean) {
    +    if (LOG.isDebugEnabled) {
    +      LOG.debug("Batch processed for sequence number: " + seqNum)
    +    }
    +    batchSuccess = success
    +    batchAckLatch.countDown()
    +  }
    +
    +  /**
    +   * Populates events into the event batch. If the batch cannot be populated,
    +   * this method will not set the event batch which will stay [[ErrorEventBatch]]
    +   */
    +  private def populateEvents() {
    +    try {
    +      txOpt = Option(channel.getTransaction)
    +      txOpt.map(tx => {
    +        tx.begin()
    +        val events = new util.ArrayList[SparkSinkEvent](maxBatchSize)
    +        val loop = new Breaks
    +        var gotEventsInThisTxn = false
    +        var loopCounter: Int = 0
    +        loop.breakable {
    +          while (events.size() < maxBatchSize
    +            && loopCounter < totalAttemptsToRemoveFromChannel) {
    +            loopCounter += 1
    +            Option(channel.take()) match {
    +              case Some(event) =>
    +                events.add(new SparkSinkEvent(toCharSequenceMap(event.getHeaders),
    +                  ByteBuffer.wrap(event.getBody)))
    +                gotEventsInThisTxn = true
    +              case None =>
    +                if (!gotEventsInThisTxn) {
    +                  TimeUnit.MILLISECONDS.sleep(500)
    +                } else {
    +                  loop.break()
    +                }
    +            }
    +          }
    +        }
    +        if (!gotEventsInThisTxn) {
    +          throw new FlumeException("Tried too many times, didn't get any events from the channel")
    +        }
    +        // At this point, the events are available, so fill them into the event batch
    +        eventBatch = new EventBatch(seqNum, events)
    +      })
    +    } catch {
    +      case e: Throwable =>
    +        LOG.error("Error while processing transaction.", e)
    +        try {
    +          txOpt.map(tx => {
    +            rollbackAndClose(tx, close = true)
    +          })
    +        } finally {
    +          // Avro might serialize the exception and cause a NACK,
    +          // so don't bother with the transaction
    +          txOpt = None
    +        }
    +    } finally {
    +      batchGeneratedLatch.countDown()
    +    }
    +  }
    +
    +  /**
    +   * Waits for upto [[transactionTimeout]] seconds for an ACK. If an ACK comes in,
    +   * this method commits the transaction with the channel. If the ACK does not come in within
    +   * that time or a NACK comes in, this method rolls back the transaction.
    +   */
    +  private def processAckOrNack() {
    +    batchAckLatch.await(transactionTimeout, TimeUnit.SECONDS)
    +    txOpt.map(tx => {
    +      if (batchSuccess) {
    +        try {
    +          tx.commit()
    +        } catch {
    +          case e: Throwable =>
    +            rollbackAndClose(tx, close = false) // tx will be closed later anyway
    --- End diff --
    
    The rollbackAndClose method actually logs it


---
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 infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] spark pull request: SPARK-1729. Make Flume pull data from source, ...

Posted by tdas <gi...@git.apache.org>.
Github user tdas commented on a diff in the pull request:

    https://github.com/apache/spark/pull/807#discussion_r13472527
  
    --- Diff: external/flume-sink/src/main/scala/org/apache/spark/flume/sink/SparkSink.scala ---
    @@ -0,0 +1,392 @@
    +/*
    + * 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.flume.sink
    +
    +import org.apache.flume.sink.AbstractSink
    +import java.util.concurrent.locks.ReentrantLock
    +import org.apache.flume.Sink.Status
    +import org.apache.spark.flume.{SparkSinkEvent, EventBatch, SparkFlumeProtocol}
    +import scala.util.control.Breaks
    +import java.nio.ByteBuffer
    +import org.apache.flume.{FlumeException, Context}
    +import org.slf4j.LoggerFactory
    +import java.util.concurrent.atomic.AtomicLong
    +import org.apache.commons.lang.RandomStringUtils
    +import java.util.concurrent._
    +import java.util
    +import org.apache.flume.conf.{ConfigurationException, Configurable}
    +import com.google.common.util.concurrent.ThreadFactoryBuilder
    +import org.apache.avro.ipc.NettyServer
    +import org.apache.avro.ipc.specific.SpecificResponder
    +import java.net.InetSocketAddress
    +
    +class SparkSink() extends AbstractSink with Configurable {
    +  private val LOG = LoggerFactory.getLogger(this.getClass)
    +  private val lock = new ReentrantLock()
    +  private val blockingCondition = lock.newCondition()
    +
    +  // This sink will not persist sequence numbers and reuses them if it gets restarted.
    +  // So it is possible to commit a transaction which may have been meant for the sink before the
    +  // restart.
    +  // Since the new txn may not have the same sequence number we must guard against accidentally
    +  // committing
    +  // a new transaction. To reduce the probability of that happening a random string is prepended
    +  // to the sequence number.
    +  // Does not change for life of sink
    +  private val seqBase = RandomStringUtils.randomAlphanumeric(8)
    +  // Incremented for each transaction
    +  private val seqNum = new AtomicLong(0)
    +
    +  private var transactionExecutorOpt: Option[ExecutorService] = None
    +
    +  private var numProcessors: Integer = SparkSinkConfig.DEFAULT_PROCESSOR_COUNT
    +  private var transactionTimeout = SparkSinkConfig.DEFAULT_TRANSACTION_TIMEOUT
    +
    +  private val processorMap = new ConcurrentHashMap[CharSequence, TransactionProcessor]()
    +
    +  private var processorFactory: Option[SparkHandlerFactory] = None
    +  private var hostname: String = SparkSinkConfig.DEFAULT_HOSTNAME
    +  private var port: Int = 0
    +  private var maxThreads: Int = SparkSinkConfig.DEFAULT_MAX_THREADS
    +  private var serverOpt: Option[NettyServer] = None
    +  private var running = false
    +
    +  override def start() {
    +    transactionExecutorOpt = Option(Executors.newFixedThreadPool(numProcessors,
    +      new ThreadFactoryBuilder().setDaemon(true)
    +        .setNameFormat("Spark Sink, " + getName + " Processor Thread - %d").build()))
    +
    +    processorFactory = Option(new SparkHandlerFactory(numProcessors))
    +
    +    val responder = new SpecificResponder(classOf[SparkFlumeProtocol], new AvroCallbackHandler())
    +
    +    // Using the constructor that takes specific thread-pools requires bringing in netty
    +    // dependencies which are being excluded in the build. In practice,
    +    // Netty dependencies are already available on the JVM as Flume would have pulled them in.
    +    serverOpt = Option(new NettyServer(responder, new InetSocketAddress(hostname, port)))
    +
    +    serverOpt.map(server => server.start())
    +    lock.lock()
    +    try {
    +      running = true
    +    } finally {
    +      lock.unlock()
    +    }
    +    super.start()
    +  }
    +
    +  override def stop() {
    +    transactionExecutorOpt.map(executor => executor.shutdownNow())
    +    serverOpt.map(server => {
    +      server.close()
    +      server.join()
    +    })
    +    lock.lock()
    +    try {
    +      running = false
    +      blockingCondition.signalAll()
    +    } finally {
    +      lock.unlock()
    +    }
    +  }
    +
    +  override def configure(ctx: Context) {
    +    import SparkSinkConfig._
    +    hostname = ctx.getString(CONF_HOSTNAME, DEFAULT_HOSTNAME)
    +    val portOpt = Option(ctx.getInteger(CONF_PORT))
    +    if(portOpt.isDefined) {
    +      port = portOpt.get
    +    } else {
    +      throw new ConfigurationException("The Port to bind must be specified")
    +    }
    +    numProcessors = ctx.getInteger(PROCESSOR_COUNT, DEFAULT_PROCESSOR_COUNT)
    +    transactionTimeout = ctx.getInteger(CONF_TRANSACTION_TIMEOUT, DEFAULT_TRANSACTION_TIMEOUT)
    +    maxThreads = ctx.getInteger(CONF_MAX_THREADS, DEFAULT_MAX_THREADS)
    +  }
    +
    +  override def process(): Status = {
    +    // This method is called in a loop by the Flume framework - block it until the sink is
    +    // stopped to save CPU resources
    +    lock.lock()
    +    try {
    +      while(running) {
    +        blockingCondition.await()
    +      }
    +    } finally {
    +      lock.unlock()
    +    }
    +    Status.BACKOFF
    +  }
    +
    +
    +  // Object representing an empty batch returned by the txn processor due to some error.
    +  case object ErrorEventBatch extends EventBatch
    +
    +  private class AvroCallbackHandler() extends SparkFlumeProtocol {
    +
    +    override def getEventBatch(n: Int): EventBatch = {
    +      val processor = processorFactory.get.checkOut(n)
    +      transactionExecutorOpt.map(executor => executor.submit(processor))
    +      // Wait until a batch is available - can be null if some error was thrown
    +      val eventBatch = processor.eventQueue.take()
    +      eventBatch match {
    +        case ErrorEventBatch => throw new FlumeException("Something went wrong. No events" +
    +          " retrieved from channel.")
    +        case events => {
    +          processorMap.put(events.getSequenceNumber, processor)
    +          if (LOG.isDebugEnabled) {
    +            LOG.debug("Sent " + events.getEventBatch.size() +
    +              " events with sequence number: " + events.getSequenceNumber)
    +          }
    +          events
    +        }
    +      }
    +    }
    +
    +    override def ack(sequenceNumber: CharSequence): Void = {
    +      completeTransaction(sequenceNumber, success = true)
    +      null
    +    }
    +
    +    override def nack(sequenceNumber: CharSequence): Void = {
    +      completeTransaction(sequenceNumber, success = false)
    +      LOG.info("Spark failed to commit transaction. Will reattempt events.")
    +      null
    +    }
    +
    +    def completeTransaction(sequenceNumber: CharSequence, success: Boolean) {
    +      val processorOpt = Option(processorMap.remove(sequenceNumber))
    +      if (processorOpt.isDefined) {
    +        val processor = processorOpt.get
    +        processor.resultQueueUpdateLock.lock()
    +        try {
    +          // Is the sequence number the same as the one the processor is processing? If not,
    +          // don't update {
    +          if (processor.eventBatch.getSequenceNumber.equals(sequenceNumber)) {
    +            processor.resultQueue.put(success)
    +          }
    +        } finally {
    +          processor.resultQueueUpdateLock.unlock()
    +        }
    +      }
    +    }
    +  }
    +
    +  // Flume forces transactions to be thread-local (horrible, I know!)
    +  // So the sink basically spawns a new thread to pull the events out within a transaction.
    +  // The thread fills in the event batch object that is set before the thread is scheduled.
    +  // After filling it in, the thread waits on a condition - which is released only
    +  // when the success message comes back for the specific sequence number for that event batch.
    +  /**
    +   * This class represents a transaction on the Flume channel. This class runs a separate thread
    +   * which owns the transaction. It is blocked until the success call for that transaction comes
    +   * back.
    +   * @param maxBatchSize
    +   */
    +  private class TransactionProcessor(var maxBatchSize: Int) extends Callable[Void] {
    +    // Must be set to a new event batch before scheduling this!!
    +    val eventBatch = new EventBatch("", new util.LinkedList[SparkSinkEvent])
    +    val eventQueue = new SynchronousQueue[EventBatch]()
    +    val resultQueue = new SynchronousQueue[Boolean]()
    +    val resultQueueUpdateLock = new ReentrantLock()
    +
    +    object Zero {
    +      val zero = "0" // Oh, I miss static finals
    +    }
    +
    +
    +    override def call(): Void = {
    +      val tx = getChannel.getTransaction
    +      tx.begin()
    +      try {
    +        eventBatch.setSequenceNumber(seqBase + seqNum.incrementAndGet())
    +        val events = eventBatch.getEventBatch
    +        events.clear()
    +        val loop = new Breaks
    +        var gotEventsInThisTxn = false
    +        loop.breakable {
    +          var i = 0
    +          // Using for here causes the maxBatchSize change to be ineffective as the Range gets
    +          // pregenerated
    +          while (i < maxBatchSize) {
    +            i += 1
    +            val eventOpt = Option(getChannel.take())
    +            eventOpt.map(event => {
    +              events.add(new SparkSinkEvent(toCharSequenceMap(event
    +                .getHeaders),
    +                ByteBuffer.wrap(event.getBody)))
    +              gotEventsInThisTxn = true
    +            })
    +            if (eventOpt.isEmpty) {
    +              if (!gotEventsInThisTxn) {
    +                // To avoid sending empty batches, we wait till events are available backing off
    +                // between attempts to get events. Each attempt to get an event though causes one
    +                // iteration to be lost. To ensure that we still send back maxBatchSize number of
    +                // events, we cheat and increase the maxBatchSize by 1 to account for the lost
    +                // iteration. Even throwing an exception is expensive as Avro will serialize it
    +                // and send it over the wire, which is useless. Before incrementing though,
    +                // ensure that we are not anywhere near INT_MAX.
    +                if (maxBatchSize >= Int.MaxValue / 2) {
    +                  // Random sanity check
    +                  throw new RuntimeException("Safety exception - polled too many times, no events!")
    +                }
    +                maxBatchSize += 1
    +                Thread.sleep(500)
    +              } else {
    +                loop.break()
    +              }
    +            }
    +          }
    +        }
    +        // Make the data available to the sender thread
    +        eventQueue.put(eventBatch)
    +
    +        // Wait till timeout for the ack/nack
    +        val maybeResult = Option(resultQueue.poll(transactionTimeout, TimeUnit.SECONDS))
    +        // There is a race condition here.
    +        // 1. This times out.
    +        // 2. The result is empty, so timeout exception is thrown.
    +        // 3. The ack comes in before the finally block is entered
    +        // 4. The thread with the ack has a handle to this processor,
    +        // and another thread has the same processor checked out
    +        // (since the finally block was executed and the processor checked back in)
    +        // 5. The thread with the ack now updates the result queue,
    +        // so the processor thinks it is the ack for the current batch.
    +        // To avoid this - update the sequence number to "0" (with or without a result - does not
    +        // matter).
    +        // In the ack method, check if the seq number is the same as the processor's -
    +        // if they are then update the result queue. Now if the
    +        // processor updates the seq number first - the ack/nack never updates the result. If the
    +        // ack/nack updates the
    +        // result after the timeout but before the seq number is updated to "0" it does not
    +        // matter - the processor would
    +        // still timeout and the result is cleared before reusing the processor.
    +        // Unfortunately, this needs to be done from within a lock
    +        // to make sure that the new sequence number is actually visible to the ack thread
    +        // (happens-before)
    +        resultQueueUpdateLock.lock()
    +        try {
    --- End diff --
    
    My gut feeling says there should be a cleaner way of doing this. But I have to think about this. Still havent understood the threading behavior. 


---
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 infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] spark pull request: SPARK-1729. Make Flume pull data from source, ...

Posted by harishreedharan <gi...@git.apache.org>.
Github user harishreedharan commented on a diff in the pull request:

    https://github.com/apache/spark/pull/807#discussion_r13471223
  
    --- Diff: external/flume-sink/src/main/scala/org/apache/spark/flume/sink/SparkSink.scala ---
    @@ -0,0 +1,392 @@
    +/*
    + * 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.flume.sink
    +
    +import org.apache.flume.sink.AbstractSink
    +import java.util.concurrent.locks.ReentrantLock
    +import org.apache.flume.Sink.Status
    +import org.apache.spark.flume.{SparkSinkEvent, EventBatch, SparkFlumeProtocol}
    +import scala.util.control.Breaks
    +import java.nio.ByteBuffer
    +import org.apache.flume.{FlumeException, Context}
    +import org.slf4j.LoggerFactory
    +import java.util.concurrent.atomic.AtomicLong
    +import org.apache.commons.lang.RandomStringUtils
    +import java.util.concurrent._
    +import java.util
    +import org.apache.flume.conf.{ConfigurationException, Configurable}
    +import com.google.common.util.concurrent.ThreadFactoryBuilder
    +import org.apache.avro.ipc.NettyServer
    +import org.apache.avro.ipc.specific.SpecificResponder
    +import java.net.InetSocketAddress
    +
    +class SparkSink() extends AbstractSink with Configurable {
    +  private val LOG = LoggerFactory.getLogger(this.getClass)
    +  private val lock = new ReentrantLock()
    +  private val blockingCondition = lock.newCondition()
    +
    +  // This sink will not persist sequence numbers and reuses them if it gets restarted.
    +  // So it is possible to commit a transaction which may have been meant for the sink before the
    +  // restart.
    +  // Since the new txn may not have the same sequence number we must guard against accidentally
    +  // committing
    +  // a new transaction. To reduce the probability of that happening a random string is prepended
    +  // to the sequence number.
    +  // Does not change for life of sink
    +  private val seqBase = RandomStringUtils.randomAlphanumeric(8)
    +  // Incremented for each transaction
    +  private val seqNum = new AtomicLong(0)
    +
    +  private var transactionExecutorOpt: Option[ExecutorService] = None
    +
    +  private var numProcessors: Integer = SparkSinkConfig.DEFAULT_PROCESSOR_COUNT
    +  private var transactionTimeout = SparkSinkConfig.DEFAULT_TRANSACTION_TIMEOUT
    +
    +  private val processorMap = new ConcurrentHashMap[CharSequence, TransactionProcessor]()
    +
    +  private var processorFactory: Option[SparkHandlerFactory] = None
    +  private var hostname: String = SparkSinkConfig.DEFAULT_HOSTNAME
    +  private var port: Int = 0
    +  private var maxThreads: Int = SparkSinkConfig.DEFAULT_MAX_THREADS
    +  private var serverOpt: Option[NettyServer] = None
    +  private var running = false
    +
    +  override def start() {
    +    transactionExecutorOpt = Option(Executors.newFixedThreadPool(numProcessors,
    +      new ThreadFactoryBuilder().setDaemon(true)
    +        .setNameFormat("Spark Sink, " + getName + " Processor Thread - %d").build()))
    +
    +    processorFactory = Option(new SparkHandlerFactory(numProcessors))
    +
    +    val responder = new SpecificResponder(classOf[SparkFlumeProtocol], new AvroCallbackHandler())
    +
    +    // Using the constructor that takes specific thread-pools requires bringing in netty
    +    // dependencies which are being excluded in the build. In practice,
    +    // Netty dependencies are already available on the JVM as Flume would have pulled them in.
    +    serverOpt = Option(new NettyServer(responder, new InetSocketAddress(hostname, port)))
    +
    +    serverOpt.map(server => server.start())
    +    lock.lock()
    +    try {
    +      running = true
    +    } finally {
    +      lock.unlock()
    +    }
    +    super.start()
    +  }
    +
    +  override def stop() {
    +    transactionExecutorOpt.map(executor => executor.shutdownNow())
    +    serverOpt.map(server => {
    +      server.close()
    +      server.join()
    +    })
    +    lock.lock()
    +    try {
    +      running = false
    +      blockingCondition.signalAll()
    +    } finally {
    +      lock.unlock()
    +    }
    +  }
    +
    +  override def configure(ctx: Context) {
    +    import SparkSinkConfig._
    +    hostname = ctx.getString(CONF_HOSTNAME, DEFAULT_HOSTNAME)
    +    val portOpt = Option(ctx.getInteger(CONF_PORT))
    +    if(portOpt.isDefined) {
    +      port = portOpt.get
    +    } else {
    +      throw new ConfigurationException("The Port to bind must be specified")
    +    }
    +    numProcessors = ctx.getInteger(PROCESSOR_COUNT, DEFAULT_PROCESSOR_COUNT)
    +    transactionTimeout = ctx.getInteger(CONF_TRANSACTION_TIMEOUT, DEFAULT_TRANSACTION_TIMEOUT)
    +    maxThreads = ctx.getInteger(CONF_MAX_THREADS, DEFAULT_MAX_THREADS)
    +  }
    +
    +  override def process(): Status = {
    +    // This method is called in a loop by the Flume framework - block it until the sink is
    +    // stopped to save CPU resources
    +    lock.lock()
    +    try {
    +      while(running) {
    --- End diff --
    
    Putting waits outside loops is called naked wait, and can cause issues when signalAll is called and also when there are spurious wake ups:
    http://docs.oracle.com/javase/7/docs/api/java/lang/Object.html#wait%28long%29


---
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 infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] spark pull request: SPARK-1729. Make Flume pull data from source, ...

Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the pull request:

    https://github.com/apache/spark/pull/807#issuecomment-43393108
  
    Can one of the admins verify this patch?


---
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 infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] spark pull request: [STREAMING] SPARK-1729. Make Flume pull data f...

Posted by SparkQA <gi...@git.apache.org>.
Github user SparkQA commented on the pull request:

    https://github.com/apache/spark/pull/807#issuecomment-50417767
  
    QA results for PR 807:<br>- This patch PASSES unit tests.<br>- This patch merges cleanly<br>- This patch adds the following public classes (experimental):<br>class SparkSink extends AbstractSink with Logging with Configurable {<br><br>For more information see test ouptut:<br>https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/17313/consoleFull


---
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 infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] spark pull request: SPARK-1729. Make Flume pull data from source, ...

Posted by tdas <gi...@git.apache.org>.
Github user tdas commented on a diff in the pull request:

    https://github.com/apache/spark/pull/807#discussion_r13833934
  
    --- Diff: external/flume-sink/src/main/scala/org/apache/spark/flume/sink/SparkSink.scala ---
    @@ -0,0 +1,432 @@
    +/*
    + * 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.flume.sink
    +
    +import java.net.InetSocketAddress
    +import java.nio.ByteBuffer
    +import java.util
    +import java.util.concurrent._
    +import java.util.concurrent.atomic.AtomicLong
    +
    +import scala.util.control.Breaks
    +
    +import com.google.common.util.concurrent.ThreadFactoryBuilder
    +import org.apache.avro.ipc.NettyServer
    +import org.apache.avro.ipc.specific.SpecificResponder
    +import org.apache.commons.lang.RandomStringUtils
    +import org.apache.flume.Sink.Status
    +import org.apache.flume.conf.{ConfigurationException, Configurable}
    +import org.apache.flume.sink.AbstractSink
    +import org.apache.flume.{Channel, Transaction, FlumeException, Context}
    +import org.slf4j.LoggerFactory
    +
    +import org.apache.spark.flume.{SparkSinkEvent, EventBatch, SparkFlumeProtocol}
    +
    +/**
    + * A sink that uses Avro RPC to run a server that can be polled by Spark's
    + * FlumePollingInputDStream. This sink has the following configuration parameters:
    + *
    + * hostname - The hostname to bind to. Default: 0.0.0.0
    + * port - The port to bind to. (No default - mandatory)
    + * timeout - Time in seconds after which a transaction is rolled back,
    + * if an ACK is not received from Spark within that time
    + * threads - Number of threads to use to receive requests from Spark (Default: 10)
    + *
    + */
    +// Flume forces transactions to be thread-local. So each transaction *must* be committed, or
    +// rolled back from the thread it was originally created in. So each getEvents call from Spark
    +// creates a TransactionProcessor which runs in a new thread, in which the transaction is created
    +// and events are pulled off the channel. Once the events are sent to spark,
    +// that thread is blocked and the TransactionProcessor is saved in a map,
    +// until an ACK or NACK comes back or the transaction times out (after the specified timeout).
    +// When the response comes, the TransactionProcessor is retrieved and then unblocked,
    +// at which point the transaction is committed or rolled back.
    +class SparkSink extends AbstractSink with Configurable {
    +
    +  // Size of the pool to use for holding transaction processors.
    +  private var poolSize: Integer = SparkSinkConfig.DEFAULT_THREADS
    +
    +  // Timeout for each transaction. If spark does not respond in this much time,
    +  // rollback the transaction
    +  private var transactionTimeout = SparkSinkConfig.DEFAULT_TRANSACTION_TIMEOUT
    +
    +  // Address info to bind on
    +  private var hostname: String = SparkSinkConfig.DEFAULT_HOSTNAME
    +  private var port: Int = 0
    +
    +  // Handle to the server
    +  private var serverOpt: Option[NettyServer] = None
    +
    +  // The handler that handles the callback from Avro
    +  private var handler: Option[SparkAvroCallbackHandler] = None
    +
    +  // Latch that blocks off the Flume framework from wasting 1 thread.
    +  private val blockingLatch = new CountDownLatch(1)
    +
    +  override def start() {
    +    handler = Option(new SparkAvroCallbackHandler(poolSize, getChannel, transactionTimeout))
    +    val responder = new SpecificResponder(classOf[SparkFlumeProtocol], handler.get)
    +    // Using the constructor that takes specific thread-pools requires bringing in netty
    +    // dependencies which are being excluded in the build. In practice,
    +    // Netty dependencies are already available on the JVM as Flume would have pulled them in.
    +    serverOpt = Option(new NettyServer(responder, new InetSocketAddress(hostname, port)))
    +    serverOpt.map(server => {
    +      server.start()
    +    })
    +    super.start()
    +  }
    +
    +  override def stop() {
    +    handler.map(callbackHandler => {
    +      callbackHandler.shutdown()
    +    })
    +    serverOpt.map(server => {
    +      server.close()
    +      server.join()
    +    })
    +    blockingLatch.countDown()
    +    super.stop()
    +  }
    +
    +  /**
    +   * @param ctx
    +   */
    +  override def configure(ctx: Context) {
    +    import SparkSinkConfig._
    +    hostname = ctx.getString(CONF_HOSTNAME, DEFAULT_HOSTNAME)
    +    port = Option(ctx.getInteger(CONF_PORT)).
    +      getOrElse(throw new ConfigurationException("The port to bind to must be specified"))
    +    poolSize = ctx.getInteger(THREADS, DEFAULT_THREADS)
    +    transactionTimeout = ctx.getInteger(CONF_TRANSACTION_TIMEOUT, DEFAULT_TRANSACTION_TIMEOUT)
    +  }
    +
    +  override def process(): Status = {
    +    // This method is called in a loop by the Flume framework - block it until the sink is
    +    // stopped to save CPU resources. The sink runner will interrupt this thread when the sink is
    +    // being shut down.
    +    blockingLatch.await()
    +    Status.BACKOFF
    +  }
    +}
    +
    +/**
    + * Class that implements the SparkFlumeProtocol, that is used by the Avro Netty Server to process
    + * requests. Each getEvents, ack and nack call is forwarded to an instance of this class.
    + * @param threads Number of threads to use to process requests.
    + * @param channel The channel that the sink pulls events from
    + * @param transactionTimeout Timeout in millis after which the transaction if not acked by Spark
    + *                           is rolled back.
    + */
    +private class SparkAvroCallbackHandler(val threads: Int, val channel: Channel,
    +  val transactionTimeout: Int) extends SparkFlumeProtocol {
    +  private val LOG = LoggerFactory.getLogger(classOf[SparkAvroCallbackHandler])
    +  val transactionExecutorOpt = Option(Executors.newFixedThreadPool(threads,
    +    new ThreadFactoryBuilder().setDaemon(true)
    +      .setNameFormat("Spark Sink Processor Thread - %d").build()))
    +  private val processorMap = new ConcurrentHashMap[CharSequence, TransactionProcessor]()
    +  // This sink will not persist sequence numbers and reuses them if it gets restarted.
    +  // So it is possible to commit a transaction which may have been meant for the sink before the
    +  // restart.
    +  // Since the new txn may not have the same sequence number we must guard against accidentally
    +  // committing a new transaction. To reduce the probability of that happening a random string is
    +  // prepended to the sequence number. Does not change for life of sink
    +  private val seqBase = RandomStringUtils.randomAlphanumeric(8)
    +  private val seqCounter = new AtomicLong(0)
    +
    +  /**
    +   * Returns a bunch of events to Spark over Avro RPC.
    +   * @param n Maximum number of events to return in a batch
    +   * @return [[EventBatch]] instance that has a sequence number and an array of at most n events
    +   */
    +  override def getEventBatch(n: Int): EventBatch = {
    +    val sequenceNumber = seqBase + seqCounter.incrementAndGet()
    +    val processor = new TransactionProcessor(channel, sequenceNumber,
    +      n, transactionTimeout, this)
    +    transactionExecutorOpt.map(executor => {
    +      executor.submit(processor)
    +    })
    +    // Wait until a batch is available - can be null if some error was thrown
    +    processor.getEventBatch match {
    +      case ErrorEventBatch => throw new FlumeException("Something went wrong. No events" +
    +        " retrieved from channel.")
    +      case eventBatch: EventBatch =>
    +        processorMap.put(sequenceNumber, processor)
    +        if (LOG.isDebugEnabled()) {
    +          LOG.debug("Sent " + eventBatch.getEvents.size() +
    +            " events with sequence number: " + eventBatch.getSequenceNumber)
    +        }
    +        eventBatch
    +    }
    +  }
    +
    +  /**
    +   * Called by Spark to indicate successful commit of a batch
    +   * @param sequenceNumber The sequence number of the event batch that was successful
    +   */
    +  override def ack(sequenceNumber: CharSequence): Void = {
    +    completeTransaction(sequenceNumber, success = true)
    +    null
    +  }
    +
    +  /**
    +   * Called by Spark to indicate failed commit of a batch
    +   * @param sequenceNumber The sequence number of the event batch that failed
    +   * @return
    +   */
    +  override def nack(sequenceNumber: CharSequence): Void = {
    +    completeTransaction(sequenceNumber, success = false)
    +    LOG.info("Spark failed to commit transaction. Will reattempt events.")
    +    null
    +  }
    +
    +  /**
    +   * Helper method to commit or rollback a transaction.
    +   * @param sequenceNumber The sequence number of the batch that was completed
    +   * @param success Whether the batch was successful or not.
    +   */
    +  private def completeTransaction(sequenceNumber: CharSequence, success: Boolean) {
    +    Option(removeAndGetProcessor(sequenceNumber)).map(processor => {
    +      processor.batchProcessed(success)
    +    })
    +  }
    +
    +  /**
    +   * Helper method to remove the TxnProcessor for a Sequence Number. Can be used to avoid a leak.
    +   * @param sequenceNumber
    +   * @return The transaction processor for the corresponding batch. Note that this instance is no
    +   *         longer tracked and the caller is responsible for that txn processor.
    +   */
    +  private[flume] def removeAndGetProcessor(sequenceNumber: CharSequence): TransactionProcessor = {
    +    processorMap.remove(sequenceNumber.toString) // The toString is required!
    +  }
    +
    +  /**
    +   * Shuts down the executor used to process transactions.
    +   */
    +  def shutdown() {
    +    transactionExecutorOpt.map(executor => {
    +      executor.shutdownNow()
    +    })
    +  }
    +}
    +
    +/**
    + * Object representing an empty batch returned by the txn processor due to some error.
    + */
    +case object ErrorEventBatch extends EventBatch
    +
    +// Flume forces transactions to be thread-local (horrible, I know!)
    +// So the sink basically spawns a new thread to pull the events out within a transaction.
    +// The thread fills in the event batch object that is set before the thread is scheduled.
    +// After filling it in, the thread waits on a condition - which is released only
    +// when the success message comes back for the specific sequence number for that event batch.
    +/**
    + * This class represents a transaction on the Flume channel. This class runs a separate thread
    + * which owns the transaction. The thread is blocked until the success call for that transaction
    + * comes back with an ACK or NACK.
    + * @param channel The channel from which to pull events
    + * @param seqNum The sequence number to use for the transaction. Must be unique
    + * @param maxBatchSize The maximum number of events to process per batch
    + * @param transactionTimeout Time in seconds after which a transaction must be rolled back
    + *                           without waiting for an ACK from Spark
    + * @param parent The parent [[SparkAvroCallbackHandler]] instance, for reporting timeouts
    + */
    +private class TransactionProcessor(val channel: Channel, val seqNum: String,
    +  var maxBatchSize: Int, val transactionTimeout: Int,
    +  val parent: SparkAvroCallbackHandler) extends Callable[Void] {
    +
    +  private val LOG = LoggerFactory.getLogger(classOf[TransactionProcessor])
    +
    +  // If a real batch is not returned, we always have to return an error batch.
    +  @volatile private var eventBatch: EventBatch = ErrorEventBatch
    +
    +  // Synchronization primitives
    +  val batchGeneratedLatch = new CountDownLatch(1)
    +  val batchAckLatch = new CountDownLatch(1)
    +
    +  // Sanity check to ensure we don't loop like crazy
    +  val totalAttemptsToRemoveFromChannel = Int.MaxValue / 2
    +
    +  // OK to use volatile, since the change would only make this true (otherwise it will be
    +  // changed to false - we never apply a negation operation to this) - which means the transaction
    +  // succeeded.
    +  @volatile private var batchSuccess = false
    +
    +  // The transaction that this processor would handle
    +  var txOpt: Option[Transaction] = None
    +
    +  /**
    +   * Get an event batch from the channel. This method will block until a batch of events is
    +   * available from the channel. If no events are available after a large number of attempts of
    +   * polling the channel, this method will return [[ErrorEventBatch]].
    +   *
    +   * @return An [[EventBatch]] instance with sequence number set to [[seqNum]], filled with a
    +   *         maximum of [[maxBatchSize]] events
    +   */
    +  def getEventBatch: EventBatch = {
    +    batchGeneratedLatch.await()
    +    eventBatch
    +  }
    +
    +  /**
    +   * This method is to be called by the sink when it receives an ACK or NACK from Spark. This
    +   * method is a no-op if it is called after [[transactionTimeout]] has expired since
    +   * [[getEventBatch]] returned a batch of events.
    +   * @param success True if an ACK was received and the transaction should be committed, else false.
    +   */
    +  def batchProcessed(success: Boolean) {
    +    if (LOG.isDebugEnabled) {
    +      LOG.debug("Batch processed for sequence number: " + seqNum)
    +    }
    +    batchSuccess = success
    +    batchAckLatch.countDown()
    +  }
    +
    +  /**
    +   * Populates events into the event batch. If the batch cannot be populated,
    +   * this method will not set the event batch which will stay [[ErrorEventBatch]]
    +   */
    +  private def populateEvents() {
    +    try {
    +      txOpt = Option(channel.getTransaction)
    +      txOpt.map(tx => {
    +        tx.begin()
    +        val events = new util.ArrayList[SparkSinkEvent](maxBatchSize)
    +        val loop = new Breaks
    +        var gotEventsInThisTxn = false
    +        var loopCounter: Int = 0
    +        loop.breakable {
    +          while (events.size() < maxBatchSize
    +            && loopCounter < totalAttemptsToRemoveFromChannel) {
    +            loopCounter += 1
    +            Option(channel.take()) match {
    +              case Some(event) =>
    +                events.add(new SparkSinkEvent(toCharSequenceMap(event.getHeaders),
    +                  ByteBuffer.wrap(event.getBody)))
    +                gotEventsInThisTxn = true
    +              case None =>
    +                if (!gotEventsInThisTxn) {
    +                  TimeUnit.MILLISECONDS.sleep(500)
    +                } else {
    +                  loop.break()
    +                }
    +            }
    +          }
    +        }
    +        if (!gotEventsInThisTxn) {
    +          throw new FlumeException("Tried too many times, didn't get any events from the channel")
    +        }
    +        // At this point, the events are available, so fill them into the event batch
    +        eventBatch = new EventBatch(seqNum, events)
    +      })
    +    } catch {
    +      case e: Throwable =>
    +        LOG.error("Error while processing transaction.", e)
    +        try {
    +          txOpt.map(tx => {
    +            rollbackAndClose(tx, close = true)
    +          })
    +        } finally {
    +          // Avro might serialize the exception and cause a NACK,
    +          // so don't bother with the transaction
    +          txOpt = None
    +        }
    +    } finally {
    +      batchGeneratedLatch.countDown()
    +    }
    +  }
    +
    +  /**
    +   * Waits for upto [[transactionTimeout]] seconds for an ACK. If an ACK comes in,
    +   * this method commits the transaction with the channel. If the ACK does not come in within
    +   * that time or a NACK comes in, this method rolls back the transaction.
    +   */
    +  private def processAckOrNack() {
    +    batchAckLatch.await(transactionTimeout, TimeUnit.SECONDS)
    +    txOpt.map(tx => {
    +      if (batchSuccess) {
    +        try {
    +          tx.commit()
    +        } catch {
    +          case e: Throwable =>
    +            rollbackAndClose(tx, close = false) // tx will be closed later anyway
    +        } finally {
    +          tx.close()
    --- End diff --
    
    `tx.close()` seems to be called twice here if there is an exception. Is that kosher?


---
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 infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] spark pull request: SPARK-1729. Make Flume pull data from source, ...

Posted by harishreedharan <gi...@git.apache.org>.
Github user harishreedharan commented on the pull request:

    https://github.com/apache/spark/pull/807#issuecomment-44081376
  
    The latest commit adds support for polling several flume agents.


---
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 infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] spark pull request: SPARK-1729. Make Flume pull data from source, ...

Posted by tdas <gi...@git.apache.org>.
Github user tdas commented on a diff in the pull request:

    https://github.com/apache/spark/pull/807#discussion_r13838498
  
    --- Diff: external/flume-sink/src/main/scala/org/apache/spark/flume/sink/SparkSink.scala ---
    @@ -0,0 +1,432 @@
    +/*
    + * 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.flume.sink
    +
    +import java.net.InetSocketAddress
    +import java.nio.ByteBuffer
    +import java.util
    +import java.util.concurrent._
    +import java.util.concurrent.atomic.AtomicLong
    +
    +import scala.util.control.Breaks
    +
    +import com.google.common.util.concurrent.ThreadFactoryBuilder
    +import org.apache.avro.ipc.NettyServer
    +import org.apache.avro.ipc.specific.SpecificResponder
    +import org.apache.commons.lang.RandomStringUtils
    +import org.apache.flume.Sink.Status
    +import org.apache.flume.conf.{ConfigurationException, Configurable}
    +import org.apache.flume.sink.AbstractSink
    +import org.apache.flume.{Channel, Transaction, FlumeException, Context}
    +import org.slf4j.LoggerFactory
    +
    +import org.apache.spark.flume.{SparkSinkEvent, EventBatch, SparkFlumeProtocol}
    +
    +/**
    + * A sink that uses Avro RPC to run a server that can be polled by Spark's
    + * FlumePollingInputDStream. This sink has the following configuration parameters:
    + *
    + * hostname - The hostname to bind to. Default: 0.0.0.0
    + * port - The port to bind to. (No default - mandatory)
    + * timeout - Time in seconds after which a transaction is rolled back,
    + * if an ACK is not received from Spark within that time
    + * threads - Number of threads to use to receive requests from Spark (Default: 10)
    + *
    + */
    +// Flume forces transactions to be thread-local. So each transaction *must* be committed, or
    +// rolled back from the thread it was originally created in. So each getEvents call from Spark
    +// creates a TransactionProcessor which runs in a new thread, in which the transaction is created
    +// and events are pulled off the channel. Once the events are sent to spark,
    +// that thread is blocked and the TransactionProcessor is saved in a map,
    +// until an ACK or NACK comes back or the transaction times out (after the specified timeout).
    +// When the response comes, the TransactionProcessor is retrieved and then unblocked,
    +// at which point the transaction is committed or rolled back.
    +class SparkSink extends AbstractSink with Configurable {
    +
    +  // Size of the pool to use for holding transaction processors.
    +  private var poolSize: Integer = SparkSinkConfig.DEFAULT_THREADS
    +
    +  // Timeout for each transaction. If spark does not respond in this much time,
    +  // rollback the transaction
    +  private var transactionTimeout = SparkSinkConfig.DEFAULT_TRANSACTION_TIMEOUT
    +
    +  // Address info to bind on
    +  private var hostname: String = SparkSinkConfig.DEFAULT_HOSTNAME
    +  private var port: Int = 0
    +
    +  // Handle to the server
    +  private var serverOpt: Option[NettyServer] = None
    +
    +  // The handler that handles the callback from Avro
    +  private var handler: Option[SparkAvroCallbackHandler] = None
    +
    +  // Latch that blocks off the Flume framework from wasting 1 thread.
    +  private val blockingLatch = new CountDownLatch(1)
    +
    +  override def start() {
    +    handler = Option(new SparkAvroCallbackHandler(poolSize, getChannel, transactionTimeout))
    +    val responder = new SpecificResponder(classOf[SparkFlumeProtocol], handler.get)
    +    // Using the constructor that takes specific thread-pools requires bringing in netty
    +    // dependencies which are being excluded in the build. In practice,
    +    // Netty dependencies are already available on the JVM as Flume would have pulled them in.
    +    serverOpt = Option(new NettyServer(responder, new InetSocketAddress(hostname, port)))
    +    serverOpt.map(server => {
    +      server.start()
    +    })
    +    super.start()
    +  }
    +
    +  override def stop() {
    +    handler.map(callbackHandler => {
    +      callbackHandler.shutdown()
    +    })
    +    serverOpt.map(server => {
    +      server.close()
    +      server.join()
    +    })
    +    blockingLatch.countDown()
    +    super.stop()
    +  }
    +
    +  /**
    +   * @param ctx
    +   */
    +  override def configure(ctx: Context) {
    +    import SparkSinkConfig._
    +    hostname = ctx.getString(CONF_HOSTNAME, DEFAULT_HOSTNAME)
    +    port = Option(ctx.getInteger(CONF_PORT)).
    +      getOrElse(throw new ConfigurationException("The port to bind to must be specified"))
    +    poolSize = ctx.getInteger(THREADS, DEFAULT_THREADS)
    +    transactionTimeout = ctx.getInteger(CONF_TRANSACTION_TIMEOUT, DEFAULT_TRANSACTION_TIMEOUT)
    +  }
    +
    +  override def process(): Status = {
    +    // This method is called in a loop by the Flume framework - block it until the sink is
    +    // stopped to save CPU resources. The sink runner will interrupt this thread when the sink is
    +    // being shut down.
    +    blockingLatch.await()
    +    Status.BACKOFF
    +  }
    +}
    +
    +/**
    + * Class that implements the SparkFlumeProtocol, that is used by the Avro Netty Server to process
    + * requests. Each getEvents, ack and nack call is forwarded to an instance of this class.
    + * @param threads Number of threads to use to process requests.
    + * @param channel The channel that the sink pulls events from
    + * @param transactionTimeout Timeout in millis after which the transaction if not acked by Spark
    + *                           is rolled back.
    + */
    +private class SparkAvroCallbackHandler(val threads: Int, val channel: Channel,
    +  val transactionTimeout: Int) extends SparkFlumeProtocol {
    +  private val LOG = LoggerFactory.getLogger(classOf[SparkAvroCallbackHandler])
    +  val transactionExecutorOpt = Option(Executors.newFixedThreadPool(threads,
    +    new ThreadFactoryBuilder().setDaemon(true)
    +      .setNameFormat("Spark Sink Processor Thread - %d").build()))
    +  private val processorMap = new ConcurrentHashMap[CharSequence, TransactionProcessor]()
    +  // This sink will not persist sequence numbers and reuses them if it gets restarted.
    +  // So it is possible to commit a transaction which may have been meant for the sink before the
    +  // restart.
    +  // Since the new txn may not have the same sequence number we must guard against accidentally
    +  // committing a new transaction. To reduce the probability of that happening a random string is
    +  // prepended to the sequence number. Does not change for life of sink
    +  private val seqBase = RandomStringUtils.randomAlphanumeric(8)
    +  private val seqCounter = new AtomicLong(0)
    +
    +  /**
    +   * Returns a bunch of events to Spark over Avro RPC.
    +   * @param n Maximum number of events to return in a batch
    +   * @return [[EventBatch]] instance that has a sequence number and an array of at most n events
    +   */
    +  override def getEventBatch(n: Int): EventBatch = {
    +    val sequenceNumber = seqBase + seqCounter.incrementAndGet()
    +    val processor = new TransactionProcessor(channel, sequenceNumber,
    +      n, transactionTimeout, this)
    +    transactionExecutorOpt.map(executor => {
    +      executor.submit(processor)
    +    })
    +    // Wait until a batch is available - can be null if some error was thrown
    +    processor.getEventBatch match {
    +      case ErrorEventBatch => throw new FlumeException("Something went wrong. No events" +
    +        " retrieved from channel.")
    +      case eventBatch: EventBatch =>
    +        processorMap.put(sequenceNumber, processor)
    +        if (LOG.isDebugEnabled()) {
    +          LOG.debug("Sent " + eventBatch.getEvents.size() +
    +            " events with sequence number: " + eventBatch.getSequenceNumber)
    +        }
    +        eventBatch
    +    }
    +  }
    +
    +  /**
    +   * Called by Spark to indicate successful commit of a batch
    +   * @param sequenceNumber The sequence number of the event batch that was successful
    +   */
    +  override def ack(sequenceNumber: CharSequence): Void = {
    +    completeTransaction(sequenceNumber, success = true)
    +    null
    +  }
    +
    +  /**
    +   * Called by Spark to indicate failed commit of a batch
    +   * @param sequenceNumber The sequence number of the event batch that failed
    +   * @return
    +   */
    +  override def nack(sequenceNumber: CharSequence): Void = {
    +    completeTransaction(sequenceNumber, success = false)
    +    LOG.info("Spark failed to commit transaction. Will reattempt events.")
    +    null
    +  }
    +
    +  /**
    +   * Helper method to commit or rollback a transaction.
    +   * @param sequenceNumber The sequence number of the batch that was completed
    +   * @param success Whether the batch was successful or not.
    +   */
    +  private def completeTransaction(sequenceNumber: CharSequence, success: Boolean) {
    +    Option(removeAndGetProcessor(sequenceNumber)).map(processor => {
    +      processor.batchProcessed(success)
    +    })
    +  }
    +
    +  /**
    +   * Helper method to remove the TxnProcessor for a Sequence Number. Can be used to avoid a leak.
    +   * @param sequenceNumber
    +   * @return The transaction processor for the corresponding batch. Note that this instance is no
    +   *         longer tracked and the caller is responsible for that txn processor.
    +   */
    +  private[flume] def removeAndGetProcessor(sequenceNumber: CharSequence): TransactionProcessor = {
    +    processorMap.remove(sequenceNumber.toString) // The toString is required!
    +  }
    +
    +  /**
    +   * Shuts down the executor used to process transactions.
    +   */
    +  def shutdown() {
    +    transactionExecutorOpt.map(executor => {
    +      executor.shutdownNow()
    +    })
    +  }
    +}
    +
    +/**
    + * Object representing an empty batch returned by the txn processor due to some error.
    + */
    +case object ErrorEventBatch extends EventBatch
    +
    +// Flume forces transactions to be thread-local (horrible, I know!)
    +// So the sink basically spawns a new thread to pull the events out within a transaction.
    +// The thread fills in the event batch object that is set before the thread is scheduled.
    +// After filling it in, the thread waits on a condition - which is released only
    +// when the success message comes back for the specific sequence number for that event batch.
    +/**
    + * This class represents a transaction on the Flume channel. This class runs a separate thread
    + * which owns the transaction. The thread is blocked until the success call for that transaction
    + * comes back with an ACK or NACK.
    + * @param channel The channel from which to pull events
    + * @param seqNum The sequence number to use for the transaction. Must be unique
    + * @param maxBatchSize The maximum number of events to process per batch
    + * @param transactionTimeout Time in seconds after which a transaction must be rolled back
    + *                           without waiting for an ACK from Spark
    + * @param parent The parent [[SparkAvroCallbackHandler]] instance, for reporting timeouts
    + */
    +private class TransactionProcessor(val channel: Channel, val seqNum: String,
    +  var maxBatchSize: Int, val transactionTimeout: Int,
    +  val parent: SparkAvroCallbackHandler) extends Callable[Void] {
    +
    +  private val LOG = LoggerFactory.getLogger(classOf[TransactionProcessor])
    +
    +  // If a real batch is not returned, we always have to return an error batch.
    +  @volatile private var eventBatch: EventBatch = ErrorEventBatch
    +
    +  // Synchronization primitives
    +  val batchGeneratedLatch = new CountDownLatch(1)
    +  val batchAckLatch = new CountDownLatch(1)
    +
    +  // Sanity check to ensure we don't loop like crazy
    +  val totalAttemptsToRemoveFromChannel = Int.MaxValue / 2
    +
    +  // OK to use volatile, since the change would only make this true (otherwise it will be
    +  // changed to false - we never apply a negation operation to this) - which means the transaction
    +  // succeeded.
    +  @volatile private var batchSuccess = false
    +
    +  // The transaction that this processor would handle
    +  var txOpt: Option[Transaction] = None
    +
    +  /**
    +   * Get an event batch from the channel. This method will block until a batch of events is
    +   * available from the channel. If no events are available after a large number of attempts of
    +   * polling the channel, this method will return [[ErrorEventBatch]].
    +   *
    +   * @return An [[EventBatch]] instance with sequence number set to [[seqNum]], filled with a
    +   *         maximum of [[maxBatchSize]] events
    +   */
    +  def getEventBatch: EventBatch = {
    +    batchGeneratedLatch.await()
    +    eventBatch
    +  }
    +
    +  /**
    +   * This method is to be called by the sink when it receives an ACK or NACK from Spark. This
    +   * method is a no-op if it is called after [[transactionTimeout]] has expired since
    +   * [[getEventBatch]] returned a batch of events.
    +   * @param success True if an ACK was received and the transaction should be committed, else false.
    +   */
    +  def batchProcessed(success: Boolean) {
    +    if (LOG.isDebugEnabled) {
    +      LOG.debug("Batch processed for sequence number: " + seqNum)
    +    }
    +    batchSuccess = success
    +    batchAckLatch.countDown()
    +  }
    +
    +  /**
    +   * Populates events into the event batch. If the batch cannot be populated,
    +   * this method will not set the event batch which will stay [[ErrorEventBatch]]
    +   */
    +  private def populateEvents() {
    +    try {
    +      txOpt = Option(channel.getTransaction)
    +      txOpt.map(tx => {
    +        tx.begin()
    +        val events = new util.ArrayList[SparkSinkEvent](maxBatchSize)
    +        val loop = new Breaks
    +        var gotEventsInThisTxn = false
    +        var loopCounter: Int = 0
    +        loop.breakable {
    +          while (events.size() < maxBatchSize
    +            && loopCounter < totalAttemptsToRemoveFromChannel) {
    +            loopCounter += 1
    +            Option(channel.take()) match {
    +              case Some(event) =>
    +                events.add(new SparkSinkEvent(toCharSequenceMap(event.getHeaders),
    +                  ByteBuffer.wrap(event.getBody)))
    +                gotEventsInThisTxn = true
    +              case None =>
    +                if (!gotEventsInThisTxn) {
    +                  TimeUnit.MILLISECONDS.sleep(500)
    +                } else {
    +                  loop.break()
    +                }
    +            }
    +          }
    +        }
    +        if (!gotEventsInThisTxn) {
    +          throw new FlumeException("Tried too many times, didn't get any events from the channel")
    +        }
    +        // At this point, the events are available, so fill them into the event batch
    +        eventBatch = new EventBatch(seqNum, events)
    +      })
    +    } catch {
    +      case e: Throwable =>
    --- End diff --
    
    Oh oh, btw, we should never catch Throwable in Scala (learnt about this recently). Scala subsystem uses a number of stuff throwable for control flow and catching throwables can give rise to very weird scenarios. Only exceptions should be caught, and reported, and all useful catchable things are mostly exceptions from what i have ever seen.
    
    For examples, OOMs are throwables but not exceptions and should never be caught.


---
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 infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] spark pull request: SPARK-1729. Make Flume pull data from source, ...

Posted by tdas <gi...@git.apache.org>.
Github user tdas commented on a diff in the pull request:

    https://github.com/apache/spark/pull/807#discussion_r13834803
  
    --- Diff: external/flume-sink/src/main/scala/org/apache/spark/flume/sink/SparkSink.scala ---
    @@ -0,0 +1,432 @@
    +/*
    + * 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.flume.sink
    +
    +import java.net.InetSocketAddress
    +import java.nio.ByteBuffer
    +import java.util
    +import java.util.concurrent._
    +import java.util.concurrent.atomic.AtomicLong
    +
    +import scala.util.control.Breaks
    +
    +import com.google.common.util.concurrent.ThreadFactoryBuilder
    +import org.apache.avro.ipc.NettyServer
    +import org.apache.avro.ipc.specific.SpecificResponder
    +import org.apache.commons.lang.RandomStringUtils
    +import org.apache.flume.Sink.Status
    +import org.apache.flume.conf.{ConfigurationException, Configurable}
    +import org.apache.flume.sink.AbstractSink
    +import org.apache.flume.{Channel, Transaction, FlumeException, Context}
    +import org.slf4j.LoggerFactory
    +
    +import org.apache.spark.flume.{SparkSinkEvent, EventBatch, SparkFlumeProtocol}
    +
    +/**
    + * A sink that uses Avro RPC to run a server that can be polled by Spark's
    + * FlumePollingInputDStream. This sink has the following configuration parameters:
    + *
    + * hostname - The hostname to bind to. Default: 0.0.0.0
    + * port - The port to bind to. (No default - mandatory)
    + * timeout - Time in seconds after which a transaction is rolled back,
    + * if an ACK is not received from Spark within that time
    + * threads - Number of threads to use to receive requests from Spark (Default: 10)
    + *
    + */
    +// Flume forces transactions to be thread-local. So each transaction *must* be committed, or
    +// rolled back from the thread it was originally created in. So each getEvents call from Spark
    +// creates a TransactionProcessor which runs in a new thread, in which the transaction is created
    +// and events are pulled off the channel. Once the events are sent to spark,
    +// that thread is blocked and the TransactionProcessor is saved in a map,
    +// until an ACK or NACK comes back or the transaction times out (after the specified timeout).
    +// When the response comes, the TransactionProcessor is retrieved and then unblocked,
    +// at which point the transaction is committed or rolled back.
    +class SparkSink extends AbstractSink with Configurable {
    +
    +  // Size of the pool to use for holding transaction processors.
    +  private var poolSize: Integer = SparkSinkConfig.DEFAULT_THREADS
    +
    +  // Timeout for each transaction. If spark does not respond in this much time,
    +  // rollback the transaction
    +  private var transactionTimeout = SparkSinkConfig.DEFAULT_TRANSACTION_TIMEOUT
    +
    +  // Address info to bind on
    +  private var hostname: String = SparkSinkConfig.DEFAULT_HOSTNAME
    +  private var port: Int = 0
    +
    +  // Handle to the server
    +  private var serverOpt: Option[NettyServer] = None
    +
    +  // The handler that handles the callback from Avro
    +  private var handler: Option[SparkAvroCallbackHandler] = None
    +
    +  // Latch that blocks off the Flume framework from wasting 1 thread.
    +  private val blockingLatch = new CountDownLatch(1)
    +
    +  override def start() {
    +    handler = Option(new SparkAvroCallbackHandler(poolSize, getChannel, transactionTimeout))
    +    val responder = new SpecificResponder(classOf[SparkFlumeProtocol], handler.get)
    +    // Using the constructor that takes specific thread-pools requires bringing in netty
    +    // dependencies which are being excluded in the build. In practice,
    +    // Netty dependencies are already available on the JVM as Flume would have pulled them in.
    +    serverOpt = Option(new NettyServer(responder, new InetSocketAddress(hostname, port)))
    +    serverOpt.map(server => {
    +      server.start()
    +    })
    +    super.start()
    +  }
    +
    +  override def stop() {
    +    handler.map(callbackHandler => {
    +      callbackHandler.shutdown()
    +    })
    +    serverOpt.map(server => {
    +      server.close()
    +      server.join()
    +    })
    +    blockingLatch.countDown()
    +    super.stop()
    +  }
    +
    +  /**
    +   * @param ctx
    +   */
    +  override def configure(ctx: Context) {
    +    import SparkSinkConfig._
    +    hostname = ctx.getString(CONF_HOSTNAME, DEFAULT_HOSTNAME)
    +    port = Option(ctx.getInteger(CONF_PORT)).
    +      getOrElse(throw new ConfigurationException("The port to bind to must be specified"))
    +    poolSize = ctx.getInteger(THREADS, DEFAULT_THREADS)
    +    transactionTimeout = ctx.getInteger(CONF_TRANSACTION_TIMEOUT, DEFAULT_TRANSACTION_TIMEOUT)
    +  }
    +
    +  override def process(): Status = {
    +    // This method is called in a loop by the Flume framework - block it until the sink is
    +    // stopped to save CPU resources. The sink runner will interrupt this thread when the sink is
    +    // being shut down.
    +    blockingLatch.await()
    +    Status.BACKOFF
    +  }
    +}
    +
    +/**
    + * Class that implements the SparkFlumeProtocol, that is used by the Avro Netty Server to process
    + * requests. Each getEvents, ack and nack call is forwarded to an instance of this class.
    + * @param threads Number of threads to use to process requests.
    + * @param channel The channel that the sink pulls events from
    + * @param transactionTimeout Timeout in millis after which the transaction if not acked by Spark
    + *                           is rolled back.
    + */
    +private class SparkAvroCallbackHandler(val threads: Int, val channel: Channel,
    +  val transactionTimeout: Int) extends SparkFlumeProtocol {
    +  private val LOG = LoggerFactory.getLogger(classOf[SparkAvroCallbackHandler])
    +  val transactionExecutorOpt = Option(Executors.newFixedThreadPool(threads,
    +    new ThreadFactoryBuilder().setDaemon(true)
    +      .setNameFormat("Spark Sink Processor Thread - %d").build()))
    +  private val processorMap = new ConcurrentHashMap[CharSequence, TransactionProcessor]()
    +  // This sink will not persist sequence numbers and reuses them if it gets restarted.
    +  // So it is possible to commit a transaction which may have been meant for the sink before the
    +  // restart.
    +  // Since the new txn may not have the same sequence number we must guard against accidentally
    +  // committing a new transaction. To reduce the probability of that happening a random string is
    +  // prepended to the sequence number. Does not change for life of sink
    +  private val seqBase = RandomStringUtils.randomAlphanumeric(8)
    +  private val seqCounter = new AtomicLong(0)
    +
    +  /**
    +   * Returns a bunch of events to Spark over Avro RPC.
    +   * @param n Maximum number of events to return in a batch
    +   * @return [[EventBatch]] instance that has a sequence number and an array of at most n events
    +   */
    +  override def getEventBatch(n: Int): EventBatch = {
    +    val sequenceNumber = seqBase + seqCounter.incrementAndGet()
    +    val processor = new TransactionProcessor(channel, sequenceNumber,
    +      n, transactionTimeout, this)
    +    transactionExecutorOpt.map(executor => {
    +      executor.submit(processor)
    +    })
    +    // Wait until a batch is available - can be null if some error was thrown
    +    processor.getEventBatch match {
    +      case ErrorEventBatch => throw new FlumeException("Something went wrong. No events" +
    +        " retrieved from channel.")
    +      case eventBatch: EventBatch =>
    +        processorMap.put(sequenceNumber, processor)
    +        if (LOG.isDebugEnabled()) {
    +          LOG.debug("Sent " + eventBatch.getEvents.size() +
    +            " events with sequence number: " + eventBatch.getSequenceNumber)
    +        }
    +        eventBatch
    +    }
    +  }
    +
    +  /**
    +   * Called by Spark to indicate successful commit of a batch
    +   * @param sequenceNumber The sequence number of the event batch that was successful
    +   */
    +  override def ack(sequenceNumber: CharSequence): Void = {
    +    completeTransaction(sequenceNumber, success = true)
    +    null
    +  }
    +
    +  /**
    +   * Called by Spark to indicate failed commit of a batch
    +   * @param sequenceNumber The sequence number of the event batch that failed
    +   * @return
    +   */
    +  override def nack(sequenceNumber: CharSequence): Void = {
    +    completeTransaction(sequenceNumber, success = false)
    +    LOG.info("Spark failed to commit transaction. Will reattempt events.")
    +    null
    +  }
    +
    +  /**
    +   * Helper method to commit or rollback a transaction.
    +   * @param sequenceNumber The sequence number of the batch that was completed
    +   * @param success Whether the batch was successful or not.
    +   */
    +  private def completeTransaction(sequenceNumber: CharSequence, success: Boolean) {
    +    Option(removeAndGetProcessor(sequenceNumber)).map(processor => {
    +      processor.batchProcessed(success)
    +    })
    +  }
    +
    +  /**
    +   * Helper method to remove the TxnProcessor for a Sequence Number. Can be used to avoid a leak.
    +   * @param sequenceNumber
    +   * @return The transaction processor for the corresponding batch. Note that this instance is no
    +   *         longer tracked and the caller is responsible for that txn processor.
    +   */
    +  private[flume] def removeAndGetProcessor(sequenceNumber: CharSequence): TransactionProcessor = {
    +    processorMap.remove(sequenceNumber.toString) // The toString is required!
    +  }
    +
    +  /**
    +   * Shuts down the executor used to process transactions.
    +   */
    +  def shutdown() {
    +    transactionExecutorOpt.map(executor => {
    +      executor.shutdownNow()
    +    })
    +  }
    +}
    +
    +/**
    + * Object representing an empty batch returned by the txn processor due to some error.
    + */
    +case object ErrorEventBatch extends EventBatch
    --- End diff --
    
    Actually, on second thought. It might be a good idea to actually propagate any errors in creating batches back to Spark streaming through this ErrorEventBatch, as it will make it much easier to debug if there is visibility into flume errors from  spark streaming side 


---
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 infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] spark pull request: SPARK-1729. Make Flume pull data from source, ...

Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the pull request:

    https://github.com/apache/spark/pull/807#issuecomment-43466801
  
    Merged build finished. 


---
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 infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] spark pull request: SPARK-1729. Make Flume pull data from source, ...

Posted by harishreedharan <gi...@git.apache.org>.
Github user harishreedharan commented on a diff in the pull request:

    https://github.com/apache/spark/pull/807#discussion_r13471124
  
    --- Diff: external/flume-sink/src/main/scala/org/apache/spark/flume/sink/SparkSink.scala ---
    @@ -0,0 +1,392 @@
    +/*
    + * 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.flume.sink
    +
    +import org.apache.flume.sink.AbstractSink
    +import java.util.concurrent.locks.ReentrantLock
    +import org.apache.flume.Sink.Status
    +import org.apache.spark.flume.{SparkSinkEvent, EventBatch, SparkFlumeProtocol}
    +import scala.util.control.Breaks
    +import java.nio.ByteBuffer
    +import org.apache.flume.{FlumeException, Context}
    +import org.slf4j.LoggerFactory
    +import java.util.concurrent.atomic.AtomicLong
    +import org.apache.commons.lang.RandomStringUtils
    +import java.util.concurrent._
    +import java.util
    +import org.apache.flume.conf.{ConfigurationException, Configurable}
    +import com.google.common.util.concurrent.ThreadFactoryBuilder
    +import org.apache.avro.ipc.NettyServer
    +import org.apache.avro.ipc.specific.SpecificResponder
    +import java.net.InetSocketAddress
    +
    +class SparkSink() extends AbstractSink with Configurable {
    +  private val LOG = LoggerFactory.getLogger(this.getClass)
    +  private val lock = new ReentrantLock()
    +  private val blockingCondition = lock.newCondition()
    +
    +  // This sink will not persist sequence numbers and reuses them if it gets restarted.
    +  // So it is possible to commit a transaction which may have been meant for the sink before the
    +  // restart.
    +  // Since the new txn may not have the same sequence number we must guard against accidentally
    +  // committing
    +  // a new transaction. To reduce the probability of that happening a random string is prepended
    +  // to the sequence number.
    +  // Does not change for life of sink
    +  private val seqBase = RandomStringUtils.randomAlphanumeric(8)
    +  // Incremented for each transaction
    +  private val seqNum = new AtomicLong(0)
    +
    +  private var transactionExecutorOpt: Option[ExecutorService] = None
    +
    +  private var numProcessors: Integer = SparkSinkConfig.DEFAULT_PROCESSOR_COUNT
    +  private var transactionTimeout = SparkSinkConfig.DEFAULT_TRANSACTION_TIMEOUT
    +
    +  private val processorMap = new ConcurrentHashMap[CharSequence, TransactionProcessor]()
    +
    +  private var processorFactory: Option[SparkHandlerFactory] = None
    +  private var hostname: String = SparkSinkConfig.DEFAULT_HOSTNAME
    +  private var port: Int = 0
    +  private var maxThreads: Int = SparkSinkConfig.DEFAULT_MAX_THREADS
    +  private var serverOpt: Option[NettyServer] = None
    +  private var running = false
    +
    +  override def start() {
    +    transactionExecutorOpt = Option(Executors.newFixedThreadPool(numProcessors,
    +      new ThreadFactoryBuilder().setDaemon(true)
    +        .setNameFormat("Spark Sink, " + getName + " Processor Thread - %d").build()))
    +
    +    processorFactory = Option(new SparkHandlerFactory(numProcessors))
    +
    +    val responder = new SpecificResponder(classOf[SparkFlumeProtocol], new AvroCallbackHandler())
    +
    +    // Using the constructor that takes specific thread-pools requires bringing in netty
    +    // dependencies which are being excluded in the build. In practice,
    +    // Netty dependencies are already available on the JVM as Flume would have pulled them in.
    +    serverOpt = Option(new NettyServer(responder, new InetSocketAddress(hostname, port)))
    +
    +    serverOpt.map(server => server.start())
    +    lock.lock()
    +    try {
    +      running = true
    +    } finally {
    +      lock.unlock()
    +    }
    +    super.start()
    +  }
    +
    +  override def stop() {
    +    transactionExecutorOpt.map(executor => executor.shutdownNow())
    +    serverOpt.map(server => {
    +      server.close()
    +      server.join()
    +    })
    +    lock.lock()
    +    try {
    +      running = false
    +      blockingCondition.signalAll()
    +    } finally {
    +      lock.unlock()
    +    }
    +  }
    +
    +  override def configure(ctx: Context) {
    +    import SparkSinkConfig._
    +    hostname = ctx.getString(CONF_HOSTNAME, DEFAULT_HOSTNAME)
    +    val portOpt = Option(ctx.getInteger(CONF_PORT))
    +    if(portOpt.isDefined) {
    +      port = portOpt.get
    +    } else {
    +      throw new ConfigurationException("The Port to bind must be specified")
    +    }
    +    numProcessors = ctx.getInteger(PROCESSOR_COUNT, DEFAULT_PROCESSOR_COUNT)
    +    transactionTimeout = ctx.getInteger(CONF_TRANSACTION_TIMEOUT, DEFAULT_TRANSACTION_TIMEOUT)
    +    maxThreads = ctx.getInteger(CONF_MAX_THREADS, DEFAULT_MAX_THREADS)
    +  }
    +
    +  override def process(): Status = {
    +    // This method is called in a loop by the Flume framework - block it until the sink is
    +    // stopped to save CPU resources
    +    lock.lock()
    +    try {
    +      while(running) {
    +        blockingCondition.await()
    +      }
    +    } finally {
    +      lock.unlock()
    +    }
    +    Status.BACKOFF
    +  }
    +
    +
    +  // Object representing an empty batch returned by the txn processor due to some error.
    +  case object ErrorEventBatch extends EventBatch
    +
    +  private class AvroCallbackHandler() extends SparkFlumeProtocol {
    +
    +    override def getEventBatch(n: Int): EventBatch = {
    +      val processor = processorFactory.get.checkOut(n)
    +      transactionExecutorOpt.map(executor => executor.submit(processor))
    +      // Wait until a batch is available - can be null if some error was thrown
    +      val eventBatch = processor.eventQueue.take()
    +      eventBatch match {
    +        case ErrorEventBatch => throw new FlumeException("Something went wrong. No events" +
    +          " retrieved from channel.")
    +        case events => {
    +          processorMap.put(events.getSequenceNumber, processor)
    +          if (LOG.isDebugEnabled) {
    +            LOG.debug("Sent " + events.getEventBatch.size() +
    +              " events with sequence number: " + events.getSequenceNumber)
    +          }
    +          events
    +        }
    +      }
    +    }
    +
    +    override def ack(sequenceNumber: CharSequence): Void = {
    +      completeTransaction(sequenceNumber, success = true)
    +      null
    +    }
    +
    +    override def nack(sequenceNumber: CharSequence): Void = {
    +      completeTransaction(sequenceNumber, success = false)
    +      LOG.info("Spark failed to commit transaction. Will reattempt events.")
    +      null
    +    }
    +
    +    def completeTransaction(sequenceNumber: CharSequence, success: Boolean) {
    +      val processorOpt = Option(processorMap.remove(sequenceNumber))
    +      if (processorOpt.isDefined) {
    +        val processor = processorOpt.get
    +        processor.resultQueueUpdateLock.lock()
    +        try {
    +          // Is the sequence number the same as the one the processor is processing? If not,
    +          // don't update {
    +          if (processor.eventBatch.getSequenceNumber.equals(sequenceNumber)) {
    +            processor.resultQueue.put(success)
    +          }
    +        } finally {
    +          processor.resultQueueUpdateLock.unlock()
    +        }
    +      }
    +    }
    +  }
    +
    +  // Flume forces transactions to be thread-local (horrible, I know!)
    +  // So the sink basically spawns a new thread to pull the events out within a transaction.
    +  // The thread fills in the event batch object that is set before the thread is scheduled.
    +  // After filling it in, the thread waits on a condition - which is released only
    +  // when the success message comes back for the specific sequence number for that event batch.
    +  /**
    +   * This class represents a transaction on the Flume channel. This class runs a separate thread
    +   * which owns the transaction. It is blocked until the success call for that transaction comes
    +   * back.
    +   * @param maxBatchSize
    +   */
    +  private class TransactionProcessor(var maxBatchSize: Int) extends Callable[Void] {
    +    // Must be set to a new event batch before scheduling this!!
    +    val eventBatch = new EventBatch("", new util.LinkedList[SparkSinkEvent])
    +    val eventQueue = new SynchronousQueue[EventBatch]()
    +    val resultQueue = new SynchronousQueue[Boolean]()
    +    val resultQueueUpdateLock = new ReentrantLock()
    +
    +    object Zero {
    +      val zero = "0" // Oh, I miss static finals
    +    }
    +
    +
    +    override def call(): Void = {
    +      val tx = getChannel.getTransaction
    +      tx.begin()
    +      try {
    +        eventBatch.setSequenceNumber(seqBase + seqNum.incrementAndGet())
    +        val events = eventBatch.getEventBatch
    +        events.clear()
    +        val loop = new Breaks
    +        var gotEventsInThisTxn = false
    +        loop.breakable {
    +          var i = 0
    +          // Using for here causes the maxBatchSize change to be ineffective as the Range gets
    +          // pregenerated
    +          while (i < maxBatchSize) {
    +            i += 1
    +            val eventOpt = Option(getChannel.take())
    +            eventOpt.map(event => {
    +              events.add(new SparkSinkEvent(toCharSequenceMap(event
    +                .getHeaders),
    +                ByteBuffer.wrap(event.getBody)))
    +              gotEventsInThisTxn = true
    +            })
    +            if (eventOpt.isEmpty) {
    +              if (!gotEventsInThisTxn) {
    +                // To avoid sending empty batches, we wait till events are available backing off
    +                // between attempts to get events. Each attempt to get an event though causes one
    +                // iteration to be lost. To ensure that we still send back maxBatchSize number of
    +                // events, we cheat and increase the maxBatchSize by 1 to account for the lost
    +                // iteration. Even throwing an exception is expensive as Avro will serialize it
    +                // and send it over the wire, which is useless. Before incrementing though,
    +                // ensure that we are not anywhere near INT_MAX.
    +                if (maxBatchSize >= Int.MaxValue / 2) {
    +                  // Random sanity check
    +                  throw new RuntimeException("Safety exception - polled too many times, no events!")
    +                }
    +                maxBatchSize += 1
    +                Thread.sleep(500)
    +              } else {
    +                loop.break()
    +              }
    +            }
    +          }
    +        }
    +        // Make the data available to the sender thread
    +        eventQueue.put(eventBatch)
    +
    +        // Wait till timeout for the ack/nack
    +        val maybeResult = Option(resultQueue.poll(transactionTimeout, TimeUnit.SECONDS))
    +        // There is a race condition here.
    +        // 1. This times out.
    +        // 2. The result is empty, so timeout exception is thrown.
    +        // 3. The ack comes in before the finally block is entered
    +        // 4. The thread with the ack has a handle to this processor,
    +        // and another thread has the same processor checked out
    +        // (since the finally block was executed and the processor checked back in)
    +        // 5. The thread with the ack now updates the result queue,
    +        // so the processor thinks it is the ack for the current batch.
    +        // To avoid this - update the sequence number to "0" (with or without a result - does not
    +        // matter).
    +        // In the ack method, check if the seq number is the same as the processor's -
    +        // if they are then update the result queue. Now if the
    +        // processor updates the seq number first - the ack/nack never updates the result. If the
    +        // ack/nack updates the
    +        // result after the timeout but before the seq number is updated to "0" it does not
    +        // matter - the processor would
    +        // still timeout and the result is cleared before reusing the processor.
    +        // Unfortunately, this needs to be done from within a lock
    +        // to make sure that the new sequence number is actually visible to the ack thread
    +        // (happens-before)
    +        resultQueueUpdateLock.lock()
    +        try {
    +          eventBatch.setSequenceNumber(Zero.zero)
    +        } finally {
    +          resultQueueUpdateLock.unlock()
    +        }
    +        eventBatch.getEventBatch.clear()
    +        // If the batch failed on spark side, throw a FlumeException
    +        maybeResult.map(success =>
    +          if (!success) {
    +            throw new
    +                FlumeException("Spark could not accept events. The transaction will be retried.")
    +          }
    +        )
    +        // If the operation timed out, throw a TimeoutException
    +        if (maybeResult.isEmpty) {
    +          throw new TimeoutException("Spark did not respond within the timeout period of " +
    +            transactionTimeout + "seconds. Transaction will be retried")
    +        }
    +        null
    +      } catch {
    +        case e: Throwable =>
    +          try {
    +            LOG.warn("Error while attempting to remove events from the channel.", e)
    +            tx.rollback()
    +          } catch {
    +            case e1: Throwable => LOG.error(
    +              "Rollback failed while attempting to rollback due to commit failure.", e1)
    +          }
    +          null // No point rethrowing the exception
    +      } finally {
    +        // Must *always* release the caller thread
    +        eventQueue.put(ErrorEventBatch)
    +        // In the case of success coming after the timeout, but before resetting the seq number
    +        // remove the event from the map and then clear the value
    +        resultQueue.clear()
    +        processorMap.remove(eventBatch.getSequenceNumber)
    +        processorFactory.get.checkIn(this)
    +        tx.close()
    +      }
    +    }
    +
    +    def toCharSequenceMap(inMap: java.util.Map[String, String]): java.util.Map[CharSequence,
    +      CharSequence] = {
    +      val charSeqMap = new util.HashMap[CharSequence, CharSequence](inMap.size())
    +      charSeqMap.putAll(inMap)
    +      charSeqMap
    +    }
    +  }
    +
    +  private class SparkHandlerFactory(val maxInstances: Int) {
    +    val queue = new scala.collection.mutable.Queue[TransactionProcessor]
    +    val queueModificationLock = new ReentrantLock()
    +    var currentSize = 0
    +    val waitForCheckIn = queueModificationLock.newCondition()
    +
    +    def checkOut(n: Int): TransactionProcessor = {
    +      def getProcessor = {
    +        val processor = queue.dequeue()
    +        processor.maxBatchSize = n
    +        processor
    +      }
    +      queueModificationLock.lock()
    +      try {
    +        if (queue.size > 0) {
    +          getProcessor
    +        }
    +        else {
    +          if (currentSize < maxInstances) {
    +            currentSize += 1
    --- End diff --
    
    No, currentSize would be equal to total # of checked out instances + queue.size. We want to keep this total less than maxInstances.


---
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 infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] spark pull request: [STREAMING] SPARK-1729. Make Flume pull data f...

Posted by SparkQA <gi...@git.apache.org>.
Github user SparkQA commented on the pull request:

    https://github.com/apache/spark/pull/807#issuecomment-50422400
  
    QA results for PR 807:<br>- This patch PASSES unit tests.<br>- This patch merges cleanly<br>- This patch adds the following public classes (experimental):<br>class SparkSink extends AbstractSink with Logging with Configurable {<br><br>For more information see test ouptut:<br>https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/17317/consoleFull


---
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 infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] spark pull request: SPARK-1729. Make Flume pull data from source, ...

Posted by harishreedharan <gi...@git.apache.org>.
Github user harishreedharan commented on a diff in the pull request:

    https://github.com/apache/spark/pull/807#discussion_r13426021
  
    --- Diff: external/flume-sink/src/main/scala/org/apache/spark/flume/sink/SparkSink.scala ---
    @@ -0,0 +1,392 @@
    +/*
    + * 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.flume.sink
    +
    +import org.apache.flume.sink.AbstractSink
    +import java.util.concurrent.locks.ReentrantLock
    +import org.apache.flume.Sink.Status
    +import org.apache.spark.flume.{SparkSinkEvent, EventBatch, SparkFlumeProtocol}
    +import scala.util.control.Breaks
    +import java.nio.ByteBuffer
    +import org.apache.flume.{FlumeException, Context}
    +import org.slf4j.LoggerFactory
    +import java.util.concurrent.atomic.AtomicLong
    +import org.apache.commons.lang.RandomStringUtils
    +import java.util.concurrent._
    +import java.util
    +import org.apache.flume.conf.{ConfigurationException, Configurable}
    +import com.google.common.util.concurrent.ThreadFactoryBuilder
    +import org.apache.avro.ipc.NettyServer
    +import org.apache.avro.ipc.specific.SpecificResponder
    +import java.net.InetSocketAddress
    +
    +class SparkSink() extends AbstractSink with Configurable {
    +  private val LOG = LoggerFactory.getLogger(this.getClass)
    +  private val lock = new ReentrantLock()
    +  private val blockingCondition = lock.newCondition()
    --- End diff --
    
    Section 13.4 of Java Concurrency in Practice has a reasonable explanation of this behavior (http://my.safaribooksonline.com/book/programming/java/0321349601/explicit-locks/ch13lev1sec4). In general reentrant locks are faster when there are more threads.


---
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 infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] spark pull request: SPARK-1729. Make Flume pull data from source, ...

Posted by tdas <gi...@git.apache.org>.
Github user tdas commented on a diff in the pull request:

    https://github.com/apache/spark/pull/807#discussion_r13467223
  
    --- Diff: external/flume-sink/src/main/scala/org/apache/spark/flume/sink/SparkSink.scala ---
    @@ -0,0 +1,392 @@
    +/*
    + * 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.flume.sink
    +
    +import org.apache.flume.sink.AbstractSink
    +import java.util.concurrent.locks.ReentrantLock
    +import org.apache.flume.Sink.Status
    +import org.apache.spark.flume.{SparkSinkEvent, EventBatch, SparkFlumeProtocol}
    +import scala.util.control.Breaks
    +import java.nio.ByteBuffer
    +import org.apache.flume.{FlumeException, Context}
    +import org.slf4j.LoggerFactory
    +import java.util.concurrent.atomic.AtomicLong
    +import org.apache.commons.lang.RandomStringUtils
    +import java.util.concurrent._
    +import java.util
    +import org.apache.flume.conf.{ConfigurationException, Configurable}
    +import com.google.common.util.concurrent.ThreadFactoryBuilder
    +import org.apache.avro.ipc.NettyServer
    +import org.apache.avro.ipc.specific.SpecificResponder
    +import java.net.InetSocketAddress
    +
    +class SparkSink() extends AbstractSink with Configurable {
    +  private val LOG = LoggerFactory.getLogger(this.getClass)
    +  private val lock = new ReentrantLock()
    +  private val blockingCondition = lock.newCondition()
    +
    +  // This sink will not persist sequence numbers and reuses them if it gets restarted.
    +  // So it is possible to commit a transaction which may have been meant for the sink before the
    +  // restart.
    +  // Since the new txn may not have the same sequence number we must guard against accidentally
    +  // committing
    +  // a new transaction. To reduce the probability of that happening a random string is prepended
    +  // to the sequence number.
    +  // Does not change for life of sink
    +  private val seqBase = RandomStringUtils.randomAlphanumeric(8)
    +  // Incremented for each transaction
    +  private val seqNum = new AtomicLong(0)
    +
    +  private var transactionExecutorOpt: Option[ExecutorService] = None
    +
    +  private var numProcessors: Integer = SparkSinkConfig.DEFAULT_PROCESSOR_COUNT
    +  private var transactionTimeout = SparkSinkConfig.DEFAULT_TRANSACTION_TIMEOUT
    +
    +  private val processorMap = new ConcurrentHashMap[CharSequence, TransactionProcessor]()
    +
    +  private var processorFactory: Option[SparkHandlerFactory] = None
    +  private var hostname: String = SparkSinkConfig.DEFAULT_HOSTNAME
    +  private var port: Int = 0
    +  private var maxThreads: Int = SparkSinkConfig.DEFAULT_MAX_THREADS
    +  private var serverOpt: Option[NettyServer] = None
    +  private var running = false
    +
    +  override def start() {
    +    transactionExecutorOpt = Option(Executors.newFixedThreadPool(numProcessors,
    +      new ThreadFactoryBuilder().setDaemon(true)
    +        .setNameFormat("Spark Sink, " + getName + " Processor Thread - %d").build()))
    +
    +    processorFactory = Option(new SparkHandlerFactory(numProcessors))
    +
    +    val responder = new SpecificResponder(classOf[SparkFlumeProtocol], new AvroCallbackHandler())
    +
    +    // Using the constructor that takes specific thread-pools requires bringing in netty
    +    // dependencies which are being excluded in the build. In practice,
    +    // Netty dependencies are already available on the JVM as Flume would have pulled them in.
    +    serverOpt = Option(new NettyServer(responder, new InetSocketAddress(hostname, port)))
    +
    +    serverOpt.map(server => server.start())
    +    lock.lock()
    +    try {
    +      running = true
    +    } finally {
    +      lock.unlock()
    +    }
    +    super.start()
    +  }
    +
    +  override def stop() {
    +    transactionExecutorOpt.map(executor => executor.shutdownNow())
    +    serverOpt.map(server => {
    +      server.close()
    +      server.join()
    +    })
    +    lock.lock()
    +    try {
    +      running = false
    +      blockingCondition.signalAll()
    +    } finally {
    +      lock.unlock()
    +    }
    +  }
    +
    +  override def configure(ctx: Context) {
    +    import SparkSinkConfig._
    +    hostname = ctx.getString(CONF_HOSTNAME, DEFAULT_HOSTNAME)
    +    val portOpt = Option(ctx.getInteger(CONF_PORT))
    +    if(portOpt.isDefined) {
    +      port = portOpt.get
    +    } else {
    +      throw new ConfigurationException("The Port to bind must be specified")
    +    }
    +    numProcessors = ctx.getInteger(PROCESSOR_COUNT, DEFAULT_PROCESSOR_COUNT)
    +    transactionTimeout = ctx.getInteger(CONF_TRANSACTION_TIMEOUT, DEFAULT_TRANSACTION_TIMEOUT)
    +    maxThreads = ctx.getInteger(CONF_MAX_THREADS, DEFAULT_MAX_THREADS)
    +  }
    +
    +  override def process(): Status = {
    +    // This method is called in a loop by the Flume framework - block it until the sink is
    +    // stopped to save CPU resources
    +    lock.lock()
    +    try {
    +      while(running) {
    +        blockingCondition.await()
    +      }
    +    } finally {
    +      lock.unlock()
    +    }
    +    Status.BACKOFF
    +  }
    +
    +
    +  // Object representing an empty batch returned by the txn processor due to some error.
    +  case object ErrorEventBatch extends EventBatch
    +
    +  private class AvroCallbackHandler() extends SparkFlumeProtocol {
    +
    +    override def getEventBatch(n: Int): EventBatch = {
    +      val processor = processorFactory.get.checkOut(n)
    +      transactionExecutorOpt.map(executor => executor.submit(processor))
    +      // Wait until a batch is available - can be null if some error was thrown
    +      val eventBatch = processor.eventQueue.take()
    +      eventBatch match {
    +        case ErrorEventBatch => throw new FlumeException("Something went wrong. No events" +
    +          " retrieved from channel.")
    +        case events => {
    +          processorMap.put(events.getSequenceNumber, processor)
    +          if (LOG.isDebugEnabled) {
    +            LOG.debug("Sent " + events.getEventBatch.size() +
    +              " events with sequence number: " + events.getSequenceNumber)
    +          }
    +          events
    +        }
    +      }
    +    }
    +
    +    override def ack(sequenceNumber: CharSequence): Void = {
    +      completeTransaction(sequenceNumber, success = true)
    +      null
    +    }
    +
    +    override def nack(sequenceNumber: CharSequence): Void = {
    +      completeTransaction(sequenceNumber, success = false)
    +      LOG.info("Spark failed to commit transaction. Will reattempt events.")
    +      null
    +    }
    +
    +    def completeTransaction(sequenceNumber: CharSequence, success: Boolean) {
    +      val processorOpt = Option(processorMap.remove(sequenceNumber))
    +      if (processorOpt.isDefined) {
    +        val processor = processorOpt.get
    +        processor.resultQueueUpdateLock.lock()
    +        try {
    +          // Is the sequence number the same as the one the processor is processing? If not,
    +          // don't update {
    +          if (processor.eventBatch.getSequenceNumber.equals(sequenceNumber)) {
    +            processor.resultQueue.put(success)
    +          }
    +        } finally {
    +          processor.resultQueueUpdateLock.unlock()
    +        }
    +      }
    +    }
    +  }
    +
    +  // Flume forces transactions to be thread-local (horrible, I know!)
    +  // So the sink basically spawns a new thread to pull the events out within a transaction.
    +  // The thread fills in the event batch object that is set before the thread is scheduled.
    +  // After filling it in, the thread waits on a condition - which is released only
    +  // when the success message comes back for the specific sequence number for that event batch.
    +  /**
    +   * This class represents a transaction on the Flume channel. This class runs a separate thread
    +   * which owns the transaction. It is blocked until the success call for that transaction comes
    +   * back.
    +   * @param maxBatchSize
    +   */
    +  private class TransactionProcessor(var maxBatchSize: Int) extends Callable[Void] {
    +    // Must be set to a new event batch before scheduling this!!
    +    val eventBatch = new EventBatch("", new util.LinkedList[SparkSinkEvent])
    +    val eventQueue = new SynchronousQueue[EventBatch]()
    +    val resultQueue = new SynchronousQueue[Boolean]()
    +    val resultQueueUpdateLock = new ReentrantLock()
    +
    +    object Zero {
    +      val zero = "0" // Oh, I miss static finals
    +    }
    +
    +
    +    override def call(): Void = {
    +      val tx = getChannel.getTransaction
    +      tx.begin()
    +      try {
    +        eventBatch.setSequenceNumber(seqBase + seqNum.incrementAndGet())
    +        val events = eventBatch.getEventBatch
    +        events.clear()
    +        val loop = new Breaks
    +        var gotEventsInThisTxn = false
    +        loop.breakable {
    +          var i = 0
    +          // Using for here causes the maxBatchSize change to be ineffective as the Range gets
    +          // pregenerated
    +          while (i < maxBatchSize) {
    +            i += 1
    +            val eventOpt = Option(getChannel.take())
    +            eventOpt.map(event => {
    +              events.add(new SparkSinkEvent(toCharSequenceMap(event
    +                .getHeaders),
    +                ByteBuffer.wrap(event.getBody)))
    +              gotEventsInThisTxn = true
    +            })
    +            if (eventOpt.isEmpty) {
    +              if (!gotEventsInThisTxn) {
    +                // To avoid sending empty batches, we wait till events are available backing off
    +                // between attempts to get events. Each attempt to get an event though causes one
    +                // iteration to be lost. To ensure that we still send back maxBatchSize number of
    +                // events, we cheat and increase the maxBatchSize by 1 to account for the lost
    +                // iteration. Even throwing an exception is expensive as Avro will serialize it
    +                // and send it over the wire, which is useless. Before incrementing though,
    +                // ensure that we are not anywhere near INT_MAX.
    +                if (maxBatchSize >= Int.MaxValue / 2) {
    --- End diff --
    
    No, I meant why isnt the following logic sufficient? 
    ```
    while (events.size < maxBatchSize) {
         val eventOpt = Option(getChannel.take())     
          // do whatever you do when eventOpt is not None
          if (eventOpt.isEmpty) {
               if (!events.isEmpty) {
                   Thread.sleep(500)
               } else {
                    loop.break()
               }
          }
    }
    ```



---
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 infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] spark pull request: SPARK-1729. Make Flume pull data from source, ...

Posted by tdas <gi...@git.apache.org>.
Github user tdas commented on a diff in the pull request:

    https://github.com/apache/spark/pull/807#discussion_r13466028
  
    --- Diff: external/flume-sink/src/main/scala/org/apache/spark/flume/sink/SparkSink.scala ---
    @@ -0,0 +1,392 @@
    +/*
    + * 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.flume.sink
    +
    +import org.apache.flume.sink.AbstractSink
    +import java.util.concurrent.locks.ReentrantLock
    +import org.apache.flume.Sink.Status
    +import org.apache.spark.flume.{SparkSinkEvent, EventBatch, SparkFlumeProtocol}
    +import scala.util.control.Breaks
    +import java.nio.ByteBuffer
    +import org.apache.flume.{FlumeException, Context}
    +import org.slf4j.LoggerFactory
    +import java.util.concurrent.atomic.AtomicLong
    +import org.apache.commons.lang.RandomStringUtils
    +import java.util.concurrent._
    +import java.util
    +import org.apache.flume.conf.{ConfigurationException, Configurable}
    +import com.google.common.util.concurrent.ThreadFactoryBuilder
    +import org.apache.avro.ipc.NettyServer
    +import org.apache.avro.ipc.specific.SpecificResponder
    +import java.net.InetSocketAddress
    +
    +class SparkSink() extends AbstractSink with Configurable {
    +  private val LOG = LoggerFactory.getLogger(this.getClass)
    +  private val lock = new ReentrantLock()
    +  private val blockingCondition = lock.newCondition()
    +
    +  // This sink will not persist sequence numbers and reuses them if it gets restarted.
    +  // So it is possible to commit a transaction which may have been meant for the sink before the
    +  // restart.
    +  // Since the new txn may not have the same sequence number we must guard against accidentally
    +  // committing
    +  // a new transaction. To reduce the probability of that happening a random string is prepended
    +  // to the sequence number.
    +  // Does not change for life of sink
    +  private val seqBase = RandomStringUtils.randomAlphanumeric(8)
    +  // Incremented for each transaction
    +  private val seqNum = new AtomicLong(0)
    +
    +  private var transactionExecutorOpt: Option[ExecutorService] = None
    +
    +  private var numProcessors: Integer = SparkSinkConfig.DEFAULT_PROCESSOR_COUNT
    +  private var transactionTimeout = SparkSinkConfig.DEFAULT_TRANSACTION_TIMEOUT
    +
    +  private val processorMap = new ConcurrentHashMap[CharSequence, TransactionProcessor]()
    +
    +  private var processorFactory: Option[SparkHandlerFactory] = None
    +  private var hostname: String = SparkSinkConfig.DEFAULT_HOSTNAME
    +  private var port: Int = 0
    +  private var maxThreads: Int = SparkSinkConfig.DEFAULT_MAX_THREADS
    +  private var serverOpt: Option[NettyServer] = None
    +  private var running = false
    +
    +  override def start() {
    +    transactionExecutorOpt = Option(Executors.newFixedThreadPool(numProcessors,
    +      new ThreadFactoryBuilder().setDaemon(true)
    +        .setNameFormat("Spark Sink, " + getName + " Processor Thread - %d").build()))
    +
    +    processorFactory = Option(new SparkHandlerFactory(numProcessors))
    +
    +    val responder = new SpecificResponder(classOf[SparkFlumeProtocol], new AvroCallbackHandler())
    +
    +    // Using the constructor that takes specific thread-pools requires bringing in netty
    +    // dependencies which are being excluded in the build. In practice,
    +    // Netty dependencies are already available on the JVM as Flume would have pulled them in.
    +    serverOpt = Option(new NettyServer(responder, new InetSocketAddress(hostname, port)))
    +
    +    serverOpt.map(server => server.start())
    +    lock.lock()
    +    try {
    +      running = true
    +    } finally {
    +      lock.unlock()
    +    }
    +    super.start()
    +  }
    +
    +  override def stop() {
    +    transactionExecutorOpt.map(executor => executor.shutdownNow())
    +    serverOpt.map(server => {
    +      server.close()
    +      server.join()
    +    })
    +    lock.lock()
    +    try {
    +      running = false
    +      blockingCondition.signalAll()
    +    } finally {
    +      lock.unlock()
    +    }
    +  }
    +
    +  override def configure(ctx: Context) {
    +    import SparkSinkConfig._
    +    hostname = ctx.getString(CONF_HOSTNAME, DEFAULT_HOSTNAME)
    +    val portOpt = Option(ctx.getInteger(CONF_PORT))
    +    if(portOpt.isDefined) {
    +      port = portOpt.get
    +    } else {
    +      throw new ConfigurationException("The Port to bind must be specified")
    +    }
    +    numProcessors = ctx.getInteger(PROCESSOR_COUNT, DEFAULT_PROCESSOR_COUNT)
    +    transactionTimeout = ctx.getInteger(CONF_TRANSACTION_TIMEOUT, DEFAULT_TRANSACTION_TIMEOUT)
    +    maxThreads = ctx.getInteger(CONF_MAX_THREADS, DEFAULT_MAX_THREADS)
    +  }
    +
    +  override def process(): Status = {
    +    // This method is called in a loop by the Flume framework - block it until the sink is
    +    // stopped to save CPU resources
    +    lock.lock()
    +    try {
    +      while(running) {
    +        blockingCondition.await()
    +      }
    +    } finally {
    +      lock.unlock()
    +    }
    +    Status.BACKOFF
    +  }
    +
    +
    +  // Object representing an empty batch returned by the txn processor due to some error.
    +  case object ErrorEventBatch extends EventBatch
    +
    +  private class AvroCallbackHandler() extends SparkFlumeProtocol {
    +
    +    override def getEventBatch(n: Int): EventBatch = {
    +      val processor = processorFactory.get.checkOut(n)
    +      transactionExecutorOpt.map(executor => executor.submit(processor))
    +      // Wait until a batch is available - can be null if some error was thrown
    +      val eventBatch = processor.eventQueue.take()
    +      eventBatch match {
    +        case ErrorEventBatch => throw new FlumeException("Something went wrong. No events" +
    +          " retrieved from channel.")
    +        case events => {
    +          processorMap.put(events.getSequenceNumber, processor)
    +          if (LOG.isDebugEnabled) {
    +            LOG.debug("Sent " + events.getEventBatch.size() +
    +              " events with sequence number: " + events.getSequenceNumber)
    +          }
    +          events
    +        }
    +      }
    +    }
    +
    +    override def ack(sequenceNumber: CharSequence): Void = {
    +      completeTransaction(sequenceNumber, success = true)
    +      null
    +    }
    +
    +    override def nack(sequenceNumber: CharSequence): Void = {
    +      completeTransaction(sequenceNumber, success = false)
    +      LOG.info("Spark failed to commit transaction. Will reattempt events.")
    +      null
    +    }
    +
    +    def completeTransaction(sequenceNumber: CharSequence, success: Boolean) {
    +      val processorOpt = Option(processorMap.remove(sequenceNumber))
    +      if (processorOpt.isDefined) {
    +        val processor = processorOpt.get
    +        processor.resultQueueUpdateLock.lock()
    +        try {
    +          // Is the sequence number the same as the one the processor is processing? If not,
    +          // don't update {
    +          if (processor.eventBatch.getSequenceNumber.equals(sequenceNumber)) {
    +            processor.resultQueue.put(success)
    +          }
    +        } finally {
    +          processor.resultQueueUpdateLock.unlock()
    +        }
    +      }
    +    }
    +  }
    +
    +  // Flume forces transactions to be thread-local (horrible, I know!)
    +  // So the sink basically spawns a new thread to pull the events out within a transaction.
    +  // The thread fills in the event batch object that is set before the thread is scheduled.
    +  // After filling it in, the thread waits on a condition - which is released only
    +  // when the success message comes back for the specific sequence number for that event batch.
    +  /**
    +   * This class represents a transaction on the Flume channel. This class runs a separate thread
    +   * which owns the transaction. It is blocked until the success call for that transaction comes
    +   * back.
    +   * @param maxBatchSize
    +   */
    +  private class TransactionProcessor(var maxBatchSize: Int) extends Callable[Void] {
    +    // Must be set to a new event batch before scheduling this!!
    +    val eventBatch = new EventBatch("", new util.LinkedList[SparkSinkEvent])
    +    val eventQueue = new SynchronousQueue[EventBatch]()
    +    val resultQueue = new SynchronousQueue[Boolean]()
    +    val resultQueueUpdateLock = new ReentrantLock()
    +
    +    object Zero {
    +      val zero = "0" // Oh, I miss static finals
    +    }
    +
    +
    +    override def call(): Void = {
    +      val tx = getChannel.getTransaction
    +      tx.begin()
    +      try {
    +        eventBatch.setSequenceNumber(seqBase + seqNum.incrementAndGet())
    +        val events = eventBatch.getEventBatch
    +        events.clear()
    +        val loop = new Breaks
    +        var gotEventsInThisTxn = false
    +        loop.breakable {
    +          var i = 0
    +          // Using for here causes the maxBatchSize change to be ineffective as the Range gets
    +          // pregenerated
    +          while (i < maxBatchSize) {
    +            i += 1
    +            val eventOpt = Option(getChannel.take())
    +            eventOpt.map(event => {
    +              events.add(new SparkSinkEvent(toCharSequenceMap(event
    +                .getHeaders),
    +                ByteBuffer.wrap(event.getBody)))
    +              gotEventsInThisTxn = true
    +            })
    +            if (eventOpt.isEmpty) {
    +              if (!gotEventsInThisTxn) {
    +                // To avoid sending empty batches, we wait till events are available backing off
    +                // between attempts to get events. Each attempt to get an event though causes one
    +                // iteration to be lost. To ensure that we still send back maxBatchSize number of
    +                // events, we cheat and increase the maxBatchSize by 1 to account for the lost
    +                // iteration. Even throwing an exception is expensive as Avro will serialize it
    +                // and send it over the wire, which is useless. Before incrementing though,
    +                // ensure that we are not anywhere near INT_MAX.
    +                if (maxBatchSize >= Int.MaxValue / 2) {
    +                  // Random sanity check
    +                  throw new RuntimeException("Safety exception - polled too many times, no events!")
    +                }
    +                maxBatchSize += 1
    +                Thread.sleep(500)
    +              } else {
    +                loop.break()
    +              }
    +            }
    +          }
    +        }
    +        // Make the data available to the sender thread
    +        eventQueue.put(eventBatch)
    +
    +        // Wait till timeout for the ack/nack
    +        val maybeResult = Option(resultQueue.poll(transactionTimeout, TimeUnit.SECONDS))
    +        // There is a race condition here.
    +        // 1. This times out.
    +        // 2. The result is empty, so timeout exception is thrown.
    +        // 3. The ack comes in before the finally block is entered
    +        // 4. The thread with the ack has a handle to this processor,
    +        // and another thread has the same processor checked out
    +        // (since the finally block was executed and the processor checked back in)
    +        // 5. The thread with the ack now updates the result queue,
    +        // so the processor thinks it is the ack for the current batch.
    +        // To avoid this - update the sequence number to "0" (with or without a result - does not
    +        // matter).
    +        // In the ack method, check if the seq number is the same as the processor's -
    +        // if they are then update the result queue. Now if the
    +        // processor updates the seq number first - the ack/nack never updates the result. If the
    +        // ack/nack updates the
    +        // result after the timeout but before the seq number is updated to "0" it does not
    +        // matter - the processor would
    +        // still timeout and the result is cleared before reusing the processor.
    +        // Unfortunately, this needs to be done from within a lock
    +        // to make sure that the new sequence number is actually visible to the ack thread
    +        // (happens-before)
    +        resultQueueUpdateLock.lock()
    +        try {
    +          eventBatch.setSequenceNumber(Zero.zero)
    +        } finally {
    +          resultQueueUpdateLock.unlock()
    +        }
    +        eventBatch.getEventBatch.clear()
    +        // If the batch failed on spark side, throw a FlumeException
    +        maybeResult.map(success =>
    +          if (!success) {
    +            throw new
    +                FlumeException("Spark could not accept events. The transaction will be retried.")
    +          }
    +        )
    +        // If the operation timed out, throw a TimeoutException
    +        if (maybeResult.isEmpty) {
    +          throw new TimeoutException("Spark did not respond within the timeout period of " +
    +            transactionTimeout + "seconds. Transaction will be retried")
    +        }
    +        null
    +      } catch {
    +        case e: Throwable =>
    +          try {
    +            LOG.warn("Error while attempting to remove events from the channel.", e)
    +            tx.rollback()
    +          } catch {
    +            case e1: Throwable => LOG.error(
    +              "Rollback failed while attempting to rollback due to commit failure.", e1)
    +          }
    +          null // No point rethrowing the exception
    +      } finally {
    +        // Must *always* release the caller thread
    +        eventQueue.put(ErrorEventBatch)
    +        // In the case of success coming after the timeout, but before resetting the seq number
    +        // remove the event from the map and then clear the value
    +        resultQueue.clear()
    +        processorMap.remove(eventBatch.getSequenceNumber)
    +        processorFactory.get.checkIn(this)
    +        tx.close()
    +      }
    +    }
    +
    +    def toCharSequenceMap(inMap: java.util.Map[String, String]): java.util.Map[CharSequence,
    +      CharSequence] = {
    +      val charSeqMap = new util.HashMap[CharSequence, CharSequence](inMap.size())
    +      charSeqMap.putAll(inMap)
    +      charSeqMap
    +    }
    +  }
    +
    +  private class SparkHandlerFactory(val maxInstances: Int) {
    +    val queue = new scala.collection.mutable.Queue[TransactionProcessor]
    +    val queueModificationLock = new ReentrantLock()
    +    var currentSize = 0
    +    val waitForCheckIn = queueModificationLock.newCondition()
    +
    +    def checkOut(n: Int): TransactionProcessor = {
    +      def getProcessor = {
    +        val processor = queue.dequeue()
    +        processor.maxBatchSize = n
    +        processor
    +      }
    +      queueModificationLock.lock()
    +      try {
    +        if (queue.size > 0) {
    +          getProcessor
    +        }
    +        else {
    +          if (currentSize < maxInstances) {
    +            currentSize += 1
    +            new TransactionProcessor(n)
    +          } else {
    +            // No events in queue and cannot initialize more!
    +            // Since currentSize never reduces, queue size increasing is the only hope
    +            while (queue.size == 0 && currentSize >= maxInstances) {
    +              waitForCheckIn.await()
    +            }
    +            getProcessor
    +          }
    +        }
    +      } finally {
    +        queueModificationLock.unlock()
    +      }
    +    }
    +
    +    def checkIn(processor: TransactionProcessor) {
    +      queueModificationLock.lock()
    --- End diff --
    
    If the goal of the queue is to buffer items (i.e. `checkin` that can be picked up by a different thread (the one that calls 'checkout`), then its simpler to use something like a [ArrayBlockingQueue](http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ArrayBlockingQueue.html) or [LinkedBlockingQueue](http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/LinkedBlockingQueue.html). No need for reentrant locks.


---
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 infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] spark pull request: SPARK-1729. Make Flume pull data from source, ...

Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the pull request:

    https://github.com/apache/spark/pull/807#issuecomment-43466802
  
    
    Refer to this link for build results: https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/15074/


---
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 infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] spark pull request: [STREAMING] SPARK-1729. Make Flume pull data f...

Posted by SparkQA <gi...@git.apache.org>.
Github user SparkQA commented on the pull request:

    https://github.com/apache/spark/pull/807#issuecomment-50429225
  
    QA tests have started for PR 807. This patch merges cleanly. <br>View progress: https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/17332/consoleFull


---
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 infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] spark pull request: SPARK-1729. Make Flume pull data from source, ...

Posted by srowen <gi...@git.apache.org>.
Github user srowen commented on a diff in the pull request:

    https://github.com/apache/spark/pull/807#discussion_r12781257
  
    --- Diff: external/flume-sink/src/main/scala/org/apache/spark/flume/sink/SparkSink.scala ---
    @@ -0,0 +1,392 @@
    +/*
    + * 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.flume.sink
    +
    +import org.apache.flume.sink.AbstractSink
    +import java.util.concurrent.locks.ReentrantLock
    +import org.apache.flume.Sink.Status
    +import org.apache.spark.flume.{SparkSinkEvent, EventBatch, SparkFlumeProtocol}
    +import scala.util.control.Breaks
    +import java.nio.ByteBuffer
    +import org.apache.flume.{FlumeException, Context}
    +import org.slf4j.LoggerFactory
    +import java.util.concurrent.atomic.AtomicLong
    +import org.apache.commons.lang.RandomStringUtils
    +import java.util.concurrent._
    +import java.util
    +import org.apache.flume.conf.{ConfigurationException, Configurable}
    +import com.google.common.util.concurrent.ThreadFactoryBuilder
    +import org.apache.avro.ipc.NettyServer
    +import org.apache.avro.ipc.specific.SpecificResponder
    +import java.net.InetSocketAddress
    +
    +class SparkSink() extends AbstractSink with Configurable {
    +  private val LOG = LoggerFactory.getLogger(this.getClass)
    +  private val lock = new ReentrantLock()
    +  private val blockingCondition = lock.newCondition()
    --- End diff --
    
    What does `lock` buy that `synchronized` doesn't? or is that not idiomatic Scala?


---
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 infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] spark pull request: SPARK-1729. Make Flume pull data from source, ...

Posted by harishreedharan <gi...@git.apache.org>.
Github user harishreedharan commented on a diff in the pull request:

    https://github.com/apache/spark/pull/807#discussion_r13835062
  
    --- Diff: external/flume-sink/src/main/scala/org/apache/spark/flume/sink/SparkSink.scala ---
    @@ -0,0 +1,432 @@
    +/*
    + * 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.flume.sink
    +
    +import java.net.InetSocketAddress
    +import java.nio.ByteBuffer
    +import java.util
    +import java.util.concurrent._
    +import java.util.concurrent.atomic.AtomicLong
    +
    +import scala.util.control.Breaks
    +
    +import com.google.common.util.concurrent.ThreadFactoryBuilder
    +import org.apache.avro.ipc.NettyServer
    +import org.apache.avro.ipc.specific.SpecificResponder
    +import org.apache.commons.lang.RandomStringUtils
    +import org.apache.flume.Sink.Status
    +import org.apache.flume.conf.{ConfigurationException, Configurable}
    +import org.apache.flume.sink.AbstractSink
    +import org.apache.flume.{Channel, Transaction, FlumeException, Context}
    +import org.slf4j.LoggerFactory
    +
    +import org.apache.spark.flume.{SparkSinkEvent, EventBatch, SparkFlumeProtocol}
    +
    +/**
    + * A sink that uses Avro RPC to run a server that can be polled by Spark's
    + * FlumePollingInputDStream. This sink has the following configuration parameters:
    + *
    + * hostname - The hostname to bind to. Default: 0.0.0.0
    + * port - The port to bind to. (No default - mandatory)
    + * timeout - Time in seconds after which a transaction is rolled back,
    + * if an ACK is not received from Spark within that time
    + * threads - Number of threads to use to receive requests from Spark (Default: 10)
    + *
    + */
    +// Flume forces transactions to be thread-local. So each transaction *must* be committed, or
    +// rolled back from the thread it was originally created in. So each getEvents call from Spark
    +// creates a TransactionProcessor which runs in a new thread, in which the transaction is created
    +// and events are pulled off the channel. Once the events are sent to spark,
    +// that thread is blocked and the TransactionProcessor is saved in a map,
    +// until an ACK or NACK comes back or the transaction times out (after the specified timeout).
    +// When the response comes, the TransactionProcessor is retrieved and then unblocked,
    +// at which point the transaction is committed or rolled back.
    +class SparkSink extends AbstractSink with Configurable {
    +
    +  // Size of the pool to use for holding transaction processors.
    +  private var poolSize: Integer = SparkSinkConfig.DEFAULT_THREADS
    +
    +  // Timeout for each transaction. If spark does not respond in this much time,
    +  // rollback the transaction
    +  private var transactionTimeout = SparkSinkConfig.DEFAULT_TRANSACTION_TIMEOUT
    +
    +  // Address info to bind on
    +  private var hostname: String = SparkSinkConfig.DEFAULT_HOSTNAME
    +  private var port: Int = 0
    +
    +  // Handle to the server
    +  private var serverOpt: Option[NettyServer] = None
    +
    +  // The handler that handles the callback from Avro
    +  private var handler: Option[SparkAvroCallbackHandler] = None
    +
    +  // Latch that blocks off the Flume framework from wasting 1 thread.
    +  private val blockingLatch = new CountDownLatch(1)
    +
    +  override def start() {
    +    handler = Option(new SparkAvroCallbackHandler(poolSize, getChannel, transactionTimeout))
    +    val responder = new SpecificResponder(classOf[SparkFlumeProtocol], handler.get)
    +    // Using the constructor that takes specific thread-pools requires bringing in netty
    +    // dependencies which are being excluded in the build. In practice,
    +    // Netty dependencies are already available on the JVM as Flume would have pulled them in.
    +    serverOpt = Option(new NettyServer(responder, new InetSocketAddress(hostname, port)))
    +    serverOpt.map(server => {
    +      server.start()
    +    })
    +    super.start()
    +  }
    +
    +  override def stop() {
    +    handler.map(callbackHandler => {
    +      callbackHandler.shutdown()
    +    })
    +    serverOpt.map(server => {
    +      server.close()
    +      server.join()
    +    })
    +    blockingLatch.countDown()
    +    super.stop()
    +  }
    +
    +  /**
    +   * @param ctx
    +   */
    +  override def configure(ctx: Context) {
    +    import SparkSinkConfig._
    +    hostname = ctx.getString(CONF_HOSTNAME, DEFAULT_HOSTNAME)
    +    port = Option(ctx.getInteger(CONF_PORT)).
    +      getOrElse(throw new ConfigurationException("The port to bind to must be specified"))
    +    poolSize = ctx.getInteger(THREADS, DEFAULT_THREADS)
    +    transactionTimeout = ctx.getInteger(CONF_TRANSACTION_TIMEOUT, DEFAULT_TRANSACTION_TIMEOUT)
    +  }
    +
    +  override def process(): Status = {
    +    // This method is called in a loop by the Flume framework - block it until the sink is
    +    // stopped to save CPU resources. The sink runner will interrupt this thread when the sink is
    +    // being shut down.
    +    blockingLatch.await()
    +    Status.BACKOFF
    +  }
    +}
    +
    +/**
    + * Class that implements the SparkFlumeProtocol, that is used by the Avro Netty Server to process
    + * requests. Each getEvents, ack and nack call is forwarded to an instance of this class.
    + * @param threads Number of threads to use to process requests.
    + * @param channel The channel that the sink pulls events from
    + * @param transactionTimeout Timeout in millis after which the transaction if not acked by Spark
    + *                           is rolled back.
    + */
    +private class SparkAvroCallbackHandler(val threads: Int, val channel: Channel,
    +  val transactionTimeout: Int) extends SparkFlumeProtocol {
    +  private val LOG = LoggerFactory.getLogger(classOf[SparkAvroCallbackHandler])
    +  val transactionExecutorOpt = Option(Executors.newFixedThreadPool(threads,
    +    new ThreadFactoryBuilder().setDaemon(true)
    +      .setNameFormat("Spark Sink Processor Thread - %d").build()))
    +  private val processorMap = new ConcurrentHashMap[CharSequence, TransactionProcessor]()
    +  // This sink will not persist sequence numbers and reuses them if it gets restarted.
    +  // So it is possible to commit a transaction which may have been meant for the sink before the
    +  // restart.
    +  // Since the new txn may not have the same sequence number we must guard against accidentally
    +  // committing a new transaction. To reduce the probability of that happening a random string is
    +  // prepended to the sequence number. Does not change for life of sink
    +  private val seqBase = RandomStringUtils.randomAlphanumeric(8)
    +  private val seqCounter = new AtomicLong(0)
    +
    +  /**
    +   * Returns a bunch of events to Spark over Avro RPC.
    +   * @param n Maximum number of events to return in a batch
    +   * @return [[EventBatch]] instance that has a sequence number and an array of at most n events
    +   */
    +  override def getEventBatch(n: Int): EventBatch = {
    +    val sequenceNumber = seqBase + seqCounter.incrementAndGet()
    +    val processor = new TransactionProcessor(channel, sequenceNumber,
    +      n, transactionTimeout, this)
    +    transactionExecutorOpt.map(executor => {
    +      executor.submit(processor)
    +    })
    +    // Wait until a batch is available - can be null if some error was thrown
    +    processor.getEventBatch match {
    +      case ErrorEventBatch => throw new FlumeException("Something went wrong. No events" +
    +        " retrieved from channel.")
    +      case eventBatch: EventBatch =>
    +        processorMap.put(sequenceNumber, processor)
    +        if (LOG.isDebugEnabled()) {
    +          LOG.debug("Sent " + eventBatch.getEvents.size() +
    +            " events with sequence number: " + eventBatch.getSequenceNumber)
    +        }
    +        eventBatch
    +    }
    +  }
    +
    +  /**
    +   * Called by Spark to indicate successful commit of a batch
    +   * @param sequenceNumber The sequence number of the event batch that was successful
    +   */
    +  override def ack(sequenceNumber: CharSequence): Void = {
    +    completeTransaction(sequenceNumber, success = true)
    +    null
    +  }
    +
    +  /**
    +   * Called by Spark to indicate failed commit of a batch
    +   * @param sequenceNumber The sequence number of the event batch that failed
    +   * @return
    +   */
    +  override def nack(sequenceNumber: CharSequence): Void = {
    +    completeTransaction(sequenceNumber, success = false)
    +    LOG.info("Spark failed to commit transaction. Will reattempt events.")
    +    null
    +  }
    +
    +  /**
    +   * Helper method to commit or rollback a transaction.
    +   * @param sequenceNumber The sequence number of the batch that was completed
    +   * @param success Whether the batch was successful or not.
    +   */
    +  private def completeTransaction(sequenceNumber: CharSequence, success: Boolean) {
    +    Option(removeAndGetProcessor(sequenceNumber)).map(processor => {
    +      processor.batchProcessed(success)
    +    })
    +  }
    +
    +  /**
    +   * Helper method to remove the TxnProcessor for a Sequence Number. Can be used to avoid a leak.
    +   * @param sequenceNumber
    +   * @return The transaction processor for the corresponding batch. Note that this instance is no
    +   *         longer tracked and the caller is responsible for that txn processor.
    +   */
    +  private[flume] def removeAndGetProcessor(sequenceNumber: CharSequence): TransactionProcessor = {
    +    processorMap.remove(sequenceNumber.toString) // The toString is required!
    +  }
    +
    +  /**
    +   * Shuts down the executor used to process transactions.
    +   */
    +  def shutdown() {
    +    transactionExecutorOpt.map(executor => {
    +      executor.shutdownNow()
    +    })
    +  }
    +}
    +
    +/**
    + * Object representing an empty batch returned by the txn processor due to some error.
    + */
    +case object ErrorEventBatch extends EventBatch
    +
    +// Flume forces transactions to be thread-local (horrible, I know!)
    +// So the sink basically spawns a new thread to pull the events out within a transaction.
    +// The thread fills in the event batch object that is set before the thread is scheduled.
    +// After filling it in, the thread waits on a condition - which is released only
    +// when the success message comes back for the specific sequence number for that event batch.
    +/**
    + * This class represents a transaction on the Flume channel. This class runs a separate thread
    + * which owns the transaction. The thread is blocked until the success call for that transaction
    + * comes back with an ACK or NACK.
    + * @param channel The channel from which to pull events
    + * @param seqNum The sequence number to use for the transaction. Must be unique
    + * @param maxBatchSize The maximum number of events to process per batch
    + * @param transactionTimeout Time in seconds after which a transaction must be rolled back
    + *                           without waiting for an ACK from Spark
    + * @param parent The parent [[SparkAvroCallbackHandler]] instance, for reporting timeouts
    + */
    +private class TransactionProcessor(val channel: Channel, val seqNum: String,
    +  var maxBatchSize: Int, val transactionTimeout: Int,
    +  val parent: SparkAvroCallbackHandler) extends Callable[Void] {
    +
    +  private val LOG = LoggerFactory.getLogger(classOf[TransactionProcessor])
    +
    +  // If a real batch is not returned, we always have to return an error batch.
    +  @volatile private var eventBatch: EventBatch = ErrorEventBatch
    +
    +  // Synchronization primitives
    +  val batchGeneratedLatch = new CountDownLatch(1)
    +  val batchAckLatch = new CountDownLatch(1)
    +
    +  // Sanity check to ensure we don't loop like crazy
    +  val totalAttemptsToRemoveFromChannel = Int.MaxValue / 2
    +
    +  // OK to use volatile, since the change would only make this true (otherwise it will be
    +  // changed to false - we never apply a negation operation to this) - which means the transaction
    +  // succeeded.
    +  @volatile private var batchSuccess = false
    +
    +  // The transaction that this processor would handle
    +  var txOpt: Option[Transaction] = None
    +
    +  /**
    +   * Get an event batch from the channel. This method will block until a batch of events is
    +   * available from the channel. If no events are available after a large number of attempts of
    +   * polling the channel, this method will return [[ErrorEventBatch]].
    +   *
    +   * @return An [[EventBatch]] instance with sequence number set to [[seqNum]], filled with a
    +   *         maximum of [[maxBatchSize]] events
    +   */
    +  def getEventBatch: EventBatch = {
    +    batchGeneratedLatch.await()
    +    eventBatch
    +  }
    +
    +  /**
    +   * This method is to be called by the sink when it receives an ACK or NACK from Spark. This
    +   * method is a no-op if it is called after [[transactionTimeout]] has expired since
    +   * [[getEventBatch]] returned a batch of events.
    +   * @param success True if an ACK was received and the transaction should be committed, else false.
    +   */
    +  def batchProcessed(success: Boolean) {
    +    if (LOG.isDebugEnabled) {
    +      LOG.debug("Batch processed for sequence number: " + seqNum)
    +    }
    +    batchSuccess = success
    +    batchAckLatch.countDown()
    +  }
    +
    +  /**
    +   * Populates events into the event batch. If the batch cannot be populated,
    +   * this method will not set the event batch which will stay [[ErrorEventBatch]]
    +   */
    +  private def populateEvents() {
    +    try {
    +      txOpt = Option(channel.getTransaction)
    +      txOpt.map(tx => {
    +        tx.begin()
    +        val events = new util.ArrayList[SparkSinkEvent](maxBatchSize)
    +        val loop = new Breaks
    +        var gotEventsInThisTxn = false
    +        var loopCounter: Int = 0
    +        loop.breakable {
    +          while (events.size() < maxBatchSize
    +            && loopCounter < totalAttemptsToRemoveFromChannel) {
    +            loopCounter += 1
    +            Option(channel.take()) match {
    +              case Some(event) =>
    +                events.add(new SparkSinkEvent(toCharSequenceMap(event.getHeaders),
    +                  ByteBuffer.wrap(event.getBody)))
    +                gotEventsInThisTxn = true
    +              case None =>
    +                if (!gotEventsInThisTxn) {
    +                  TimeUnit.MILLISECONDS.sleep(500)
    --- End diff --
    
    Will do.


---
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 infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] spark pull request: SPARK-1729. Make Flume pull data from source, ...

Posted by harishreedharan <gi...@git.apache.org>.
Github user harishreedharan commented on a diff in the pull request:

    https://github.com/apache/spark/pull/807#discussion_r13826375
  
    --- Diff: external/flume/src/main/scala/org/apache/spark/streaming/flume/EventTransformer.scala ---
    @@ -0,0 +1,72 @@
    +/*
    + * 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.streaming.flume
    +
    +import java.io.{ObjectOutput, ObjectInput}
    +
    +import scala.collection.JavaConversions._
    +
    +import org.apache.spark.util.Utils
    +import org.apache.spark.Logging
    +
    +/**
    + * A simple object that provides the implementation of readExternal and writeExternal for both
    + * the wrapper classes for Flume-style Events.
    + */
    +object EventTransformer extends Logging {
    +  def readExternal(in: ObjectInput): (java.util.HashMap[CharSequence, CharSequence],
    +    Array[Byte]) = {
    +    val bodyLength = in.readInt()
    +    val bodyBuff = new Array[Byte](bodyLength)
    +    in.read(bodyBuff)
    +
    +    val numHeaders = in.readInt()
    +    val headers = new java.util.HashMap[CharSequence, CharSequence]
    +
    +    for (i <- 0 until numHeaders) {
    +      val keyLength = in.readInt()
    +      val keyBuff = new Array[Byte](keyLength)
    +      in.read(keyBuff)
    --- End diff --
    
    My bad. Fixed


---
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 infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] spark pull request: SPARK-1729. Make Flume pull data from source, ...

Posted by tdas <gi...@git.apache.org>.
Github user tdas commented on a diff in the pull request:

    https://github.com/apache/spark/pull/807#discussion_r13834027
  
    --- Diff: external/flume-sink/src/main/scala/org/apache/spark/flume/sink/SparkSink.scala ---
    @@ -0,0 +1,432 @@
    +/*
    + * 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.flume.sink
    +
    +import java.net.InetSocketAddress
    +import java.nio.ByteBuffer
    +import java.util
    +import java.util.concurrent._
    +import java.util.concurrent.atomic.AtomicLong
    +
    +import scala.util.control.Breaks
    +
    +import com.google.common.util.concurrent.ThreadFactoryBuilder
    +import org.apache.avro.ipc.NettyServer
    +import org.apache.avro.ipc.specific.SpecificResponder
    +import org.apache.commons.lang.RandomStringUtils
    +import org.apache.flume.Sink.Status
    +import org.apache.flume.conf.{ConfigurationException, Configurable}
    +import org.apache.flume.sink.AbstractSink
    +import org.apache.flume.{Channel, Transaction, FlumeException, Context}
    +import org.slf4j.LoggerFactory
    +
    +import org.apache.spark.flume.{SparkSinkEvent, EventBatch, SparkFlumeProtocol}
    +
    +/**
    + * A sink that uses Avro RPC to run a server that can be polled by Spark's
    + * FlumePollingInputDStream. This sink has the following configuration parameters:
    + *
    + * hostname - The hostname to bind to. Default: 0.0.0.0
    + * port - The port to bind to. (No default - mandatory)
    + * timeout - Time in seconds after which a transaction is rolled back,
    + * if an ACK is not received from Spark within that time
    + * threads - Number of threads to use to receive requests from Spark (Default: 10)
    + *
    + */
    +// Flume forces transactions to be thread-local. So each transaction *must* be committed, or
    +// rolled back from the thread it was originally created in. So each getEvents call from Spark
    +// creates a TransactionProcessor which runs in a new thread, in which the transaction is created
    +// and events are pulled off the channel. Once the events are sent to spark,
    +// that thread is blocked and the TransactionProcessor is saved in a map,
    +// until an ACK or NACK comes back or the transaction times out (after the specified timeout).
    +// When the response comes, the TransactionProcessor is retrieved and then unblocked,
    +// at which point the transaction is committed or rolled back.
    +class SparkSink extends AbstractSink with Configurable {
    +
    +  // Size of the pool to use for holding transaction processors.
    +  private var poolSize: Integer = SparkSinkConfig.DEFAULT_THREADS
    +
    +  // Timeout for each transaction. If spark does not respond in this much time,
    +  // rollback the transaction
    +  private var transactionTimeout = SparkSinkConfig.DEFAULT_TRANSACTION_TIMEOUT
    +
    +  // Address info to bind on
    +  private var hostname: String = SparkSinkConfig.DEFAULT_HOSTNAME
    +  private var port: Int = 0
    +
    +  // Handle to the server
    +  private var serverOpt: Option[NettyServer] = None
    +
    +  // The handler that handles the callback from Avro
    +  private var handler: Option[SparkAvroCallbackHandler] = None
    +
    +  // Latch that blocks off the Flume framework from wasting 1 thread.
    +  private val blockingLatch = new CountDownLatch(1)
    +
    +  override def start() {
    +    handler = Option(new SparkAvroCallbackHandler(poolSize, getChannel, transactionTimeout))
    +    val responder = new SpecificResponder(classOf[SparkFlumeProtocol], handler.get)
    +    // Using the constructor that takes specific thread-pools requires bringing in netty
    +    // dependencies which are being excluded in the build. In practice,
    +    // Netty dependencies are already available on the JVM as Flume would have pulled them in.
    +    serverOpt = Option(new NettyServer(responder, new InetSocketAddress(hostname, port)))
    +    serverOpt.map(server => {
    +      server.start()
    +    })
    +    super.start()
    +  }
    +
    +  override def stop() {
    +    handler.map(callbackHandler => {
    +      callbackHandler.shutdown()
    +    })
    +    serverOpt.map(server => {
    +      server.close()
    +      server.join()
    +    })
    +    blockingLatch.countDown()
    +    super.stop()
    +  }
    +
    +  /**
    +   * @param ctx
    +   */
    +  override def configure(ctx: Context) {
    +    import SparkSinkConfig._
    +    hostname = ctx.getString(CONF_HOSTNAME, DEFAULT_HOSTNAME)
    +    port = Option(ctx.getInteger(CONF_PORT)).
    +      getOrElse(throw new ConfigurationException("The port to bind to must be specified"))
    +    poolSize = ctx.getInteger(THREADS, DEFAULT_THREADS)
    +    transactionTimeout = ctx.getInteger(CONF_TRANSACTION_TIMEOUT, DEFAULT_TRANSACTION_TIMEOUT)
    +  }
    +
    +  override def process(): Status = {
    +    // This method is called in a loop by the Flume framework - block it until the sink is
    +    // stopped to save CPU resources. The sink runner will interrupt this thread when the sink is
    +    // being shut down.
    +    blockingLatch.await()
    +    Status.BACKOFF
    +  }
    +}
    +
    +/**
    + * Class that implements the SparkFlumeProtocol, that is used by the Avro Netty Server to process
    + * requests. Each getEvents, ack and nack call is forwarded to an instance of this class.
    + * @param threads Number of threads to use to process requests.
    + * @param channel The channel that the sink pulls events from
    + * @param transactionTimeout Timeout in millis after which the transaction if not acked by Spark
    + *                           is rolled back.
    + */
    +private class SparkAvroCallbackHandler(val threads: Int, val channel: Channel,
    +  val transactionTimeout: Int) extends SparkFlumeProtocol {
    +  private val LOG = LoggerFactory.getLogger(classOf[SparkAvroCallbackHandler])
    +  val transactionExecutorOpt = Option(Executors.newFixedThreadPool(threads,
    +    new ThreadFactoryBuilder().setDaemon(true)
    +      .setNameFormat("Spark Sink Processor Thread - %d").build()))
    +  private val processorMap = new ConcurrentHashMap[CharSequence, TransactionProcessor]()
    +  // This sink will not persist sequence numbers and reuses them if it gets restarted.
    +  // So it is possible to commit a transaction which may have been meant for the sink before the
    +  // restart.
    +  // Since the new txn may not have the same sequence number we must guard against accidentally
    +  // committing a new transaction. To reduce the probability of that happening a random string is
    +  // prepended to the sequence number. Does not change for life of sink
    +  private val seqBase = RandomStringUtils.randomAlphanumeric(8)
    +  private val seqCounter = new AtomicLong(0)
    +
    +  /**
    +   * Returns a bunch of events to Spark over Avro RPC.
    +   * @param n Maximum number of events to return in a batch
    +   * @return [[EventBatch]] instance that has a sequence number and an array of at most n events
    +   */
    +  override def getEventBatch(n: Int): EventBatch = {
    +    val sequenceNumber = seqBase + seqCounter.incrementAndGet()
    +    val processor = new TransactionProcessor(channel, sequenceNumber,
    +      n, transactionTimeout, this)
    +    transactionExecutorOpt.map(executor => {
    +      executor.submit(processor)
    +    })
    +    // Wait until a batch is available - can be null if some error was thrown
    +    processor.getEventBatch match {
    +      case ErrorEventBatch => throw new FlumeException("Something went wrong. No events" +
    +        " retrieved from channel.")
    +      case eventBatch: EventBatch =>
    +        processorMap.put(sequenceNumber, processor)
    +        if (LOG.isDebugEnabled()) {
    +          LOG.debug("Sent " + eventBatch.getEvents.size() +
    +            " events with sequence number: " + eventBatch.getSequenceNumber)
    +        }
    +        eventBatch
    +    }
    +  }
    +
    +  /**
    +   * Called by Spark to indicate successful commit of a batch
    +   * @param sequenceNumber The sequence number of the event batch that was successful
    +   */
    +  override def ack(sequenceNumber: CharSequence): Void = {
    +    completeTransaction(sequenceNumber, success = true)
    +    null
    +  }
    +
    +  /**
    +   * Called by Spark to indicate failed commit of a batch
    +   * @param sequenceNumber The sequence number of the event batch that failed
    +   * @return
    +   */
    +  override def nack(sequenceNumber: CharSequence): Void = {
    +    completeTransaction(sequenceNumber, success = false)
    +    LOG.info("Spark failed to commit transaction. Will reattempt events.")
    +    null
    +  }
    +
    +  /**
    +   * Helper method to commit or rollback a transaction.
    +   * @param sequenceNumber The sequence number of the batch that was completed
    +   * @param success Whether the batch was successful or not.
    +   */
    +  private def completeTransaction(sequenceNumber: CharSequence, success: Boolean) {
    +    Option(removeAndGetProcessor(sequenceNumber)).map(processor => {
    +      processor.batchProcessed(success)
    +    })
    +  }
    +
    +  /**
    +   * Helper method to remove the TxnProcessor for a Sequence Number. Can be used to avoid a leak.
    +   * @param sequenceNumber
    +   * @return The transaction processor for the corresponding batch. Note that this instance is no
    +   *         longer tracked and the caller is responsible for that txn processor.
    +   */
    +  private[flume] def removeAndGetProcessor(sequenceNumber: CharSequence): TransactionProcessor = {
    +    processorMap.remove(sequenceNumber.toString) // The toString is required!
    +  }
    +
    +  /**
    +   * Shuts down the executor used to process transactions.
    +   */
    +  def shutdown() {
    +    transactionExecutorOpt.map(executor => {
    +      executor.shutdownNow()
    +    })
    +  }
    +}
    +
    +/**
    + * Object representing an empty batch returned by the txn processor due to some error.
    + */
    +case object ErrorEventBatch extends EventBatch
    +
    +// Flume forces transactions to be thread-local (horrible, I know!)
    +// So the sink basically spawns a new thread to pull the events out within a transaction.
    +// The thread fills in the event batch object that is set before the thread is scheduled.
    +// After filling it in, the thread waits on a condition - which is released only
    +// when the success message comes back for the specific sequence number for that event batch.
    +/**
    + * This class represents a transaction on the Flume channel. This class runs a separate thread
    + * which owns the transaction. The thread is blocked until the success call for that transaction
    + * comes back with an ACK or NACK.
    + * @param channel The channel from which to pull events
    + * @param seqNum The sequence number to use for the transaction. Must be unique
    + * @param maxBatchSize The maximum number of events to process per batch
    + * @param transactionTimeout Time in seconds after which a transaction must be rolled back
    + *                           without waiting for an ACK from Spark
    + * @param parent The parent [[SparkAvroCallbackHandler]] instance, for reporting timeouts
    + */
    +private class TransactionProcessor(val channel: Channel, val seqNum: String,
    +  var maxBatchSize: Int, val transactionTimeout: Int,
    +  val parent: SparkAvroCallbackHandler) extends Callable[Void] {
    +
    +  private val LOG = LoggerFactory.getLogger(classOf[TransactionProcessor])
    +
    +  // If a real batch is not returned, we always have to return an error batch.
    +  @volatile private var eventBatch: EventBatch = ErrorEventBatch
    +
    +  // Synchronization primitives
    +  val batchGeneratedLatch = new CountDownLatch(1)
    +  val batchAckLatch = new CountDownLatch(1)
    +
    +  // Sanity check to ensure we don't loop like crazy
    +  val totalAttemptsToRemoveFromChannel = Int.MaxValue / 2
    +
    +  // OK to use volatile, since the change would only make this true (otherwise it will be
    +  // changed to false - we never apply a negation operation to this) - which means the transaction
    +  // succeeded.
    +  @volatile private var batchSuccess = false
    +
    +  // The transaction that this processor would handle
    +  var txOpt: Option[Transaction] = None
    +
    +  /**
    +   * Get an event batch from the channel. This method will block until a batch of events is
    +   * available from the channel. If no events are available after a large number of attempts of
    +   * polling the channel, this method will return [[ErrorEventBatch]].
    +   *
    +   * @return An [[EventBatch]] instance with sequence number set to [[seqNum]], filled with a
    +   *         maximum of [[maxBatchSize]] events
    +   */
    +  def getEventBatch: EventBatch = {
    +    batchGeneratedLatch.await()
    +    eventBatch
    +  }
    +
    +  /**
    +   * This method is to be called by the sink when it receives an ACK or NACK from Spark. This
    +   * method is a no-op if it is called after [[transactionTimeout]] has expired since
    +   * [[getEventBatch]] returned a batch of events.
    +   * @param success True if an ACK was received and the transaction should be committed, else false.
    +   */
    +  def batchProcessed(success: Boolean) {
    +    if (LOG.isDebugEnabled) {
    +      LOG.debug("Batch processed for sequence number: " + seqNum)
    +    }
    +    batchSuccess = success
    +    batchAckLatch.countDown()
    +  }
    +
    +  /**
    +   * Populates events into the event batch. If the batch cannot be populated,
    +   * this method will not set the event batch which will stay [[ErrorEventBatch]]
    +   */
    +  private def populateEvents() {
    +    try {
    +      txOpt = Option(channel.getTransaction)
    +      txOpt.map(tx => {
    +        tx.begin()
    +        val events = new util.ArrayList[SparkSinkEvent](maxBatchSize)
    +        val loop = new Breaks
    +        var gotEventsInThisTxn = false
    +        var loopCounter: Int = 0
    +        loop.breakable {
    +          while (events.size() < maxBatchSize
    +            && loopCounter < totalAttemptsToRemoveFromChannel) {
    +            loopCounter += 1
    +            Option(channel.take()) match {
    +              case Some(event) =>
    +                events.add(new SparkSinkEvent(toCharSequenceMap(event.getHeaders),
    +                  ByteBuffer.wrap(event.getBody)))
    +                gotEventsInThisTxn = true
    +              case None =>
    +                if (!gotEventsInThisTxn) {
    +                  TimeUnit.MILLISECONDS.sleep(500)
    +                } else {
    +                  loop.break()
    +                }
    +            }
    +          }
    +        }
    +        if (!gotEventsInThisTxn) {
    +          throw new FlumeException("Tried too many times, didn't get any events from the channel")
    +        }
    +        // At this point, the events are available, so fill them into the event batch
    +        eventBatch = new EventBatch(seqNum, events)
    +      })
    +    } catch {
    +      case e: Throwable =>
    +        LOG.error("Error while processing transaction.", e)
    +        try {
    +          txOpt.map(tx => {
    +            rollbackAndClose(tx, close = true)
    +          })
    +        } finally {
    +          // Avro might serialize the exception and cause a NACK,
    +          // so don't bother with the transaction
    +          txOpt = None
    +        }
    +    } finally {
    +      batchGeneratedLatch.countDown()
    +    }
    +  }
    +
    +  /**
    +   * Waits for upto [[transactionTimeout]] seconds for an ACK. If an ACK comes in,
    +   * this method commits the transaction with the channel. If the ACK does not come in within
    +   * that time or a NACK comes in, this method rolls back the transaction.
    +   */
    +  private def processAckOrNack() {
    +    batchAckLatch.await(transactionTimeout, TimeUnit.SECONDS)
    +    txOpt.map(tx => {
    +      if (batchSuccess) {
    +        try {
    +          tx.commit()
    +        } catch {
    +          case e: Throwable =>
    +            rollbackAndClose(tx, close = false) // tx will be closed later anyway
    --- End diff --
    
    The exception is not logged anywhere!


---
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 infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] spark pull request: SPARK-1729. Make Flume pull data from source, ...

Posted by tdas <gi...@git.apache.org>.
Github user tdas commented on a diff in the pull request:

    https://github.com/apache/spark/pull/807#discussion_r13466605
  
    --- Diff: external/flume-sink/src/main/scala/org/apache/spark/flume/sink/SparkSink.scala ---
    @@ -0,0 +1,392 @@
    +/*
    + * 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.flume.sink
    +
    +import org.apache.flume.sink.AbstractSink
    +import java.util.concurrent.locks.ReentrantLock
    +import org.apache.flume.Sink.Status
    +import org.apache.spark.flume.{SparkSinkEvent, EventBatch, SparkFlumeProtocol}
    +import scala.util.control.Breaks
    +import java.nio.ByteBuffer
    +import org.apache.flume.{FlumeException, Context}
    +import org.slf4j.LoggerFactory
    +import java.util.concurrent.atomic.AtomicLong
    +import org.apache.commons.lang.RandomStringUtils
    +import java.util.concurrent._
    +import java.util
    +import org.apache.flume.conf.{ConfigurationException, Configurable}
    +import com.google.common.util.concurrent.ThreadFactoryBuilder
    +import org.apache.avro.ipc.NettyServer
    +import org.apache.avro.ipc.specific.SpecificResponder
    +import java.net.InetSocketAddress
    +
    +class SparkSink() extends AbstractSink with Configurable {
    +  private val LOG = LoggerFactory.getLogger(this.getClass)
    +  private val lock = new ReentrantLock()
    +  private val blockingCondition = lock.newCondition()
    +
    +  // This sink will not persist sequence numbers and reuses them if it gets restarted.
    +  // So it is possible to commit a transaction which may have been meant for the sink before the
    +  // restart.
    +  // Since the new txn may not have the same sequence number we must guard against accidentally
    +  // committing
    +  // a new transaction. To reduce the probability of that happening a random string is prepended
    +  // to the sequence number.
    +  // Does not change for life of sink
    +  private val seqBase = RandomStringUtils.randomAlphanumeric(8)
    +  // Incremented for each transaction
    +  private val seqNum = new AtomicLong(0)
    +
    +  private var transactionExecutorOpt: Option[ExecutorService] = None
    +
    +  private var numProcessors: Integer = SparkSinkConfig.DEFAULT_PROCESSOR_COUNT
    +  private var transactionTimeout = SparkSinkConfig.DEFAULT_TRANSACTION_TIMEOUT
    +
    +  private val processorMap = new ConcurrentHashMap[CharSequence, TransactionProcessor]()
    +
    +  private var processorFactory: Option[SparkHandlerFactory] = None
    +  private var hostname: String = SparkSinkConfig.DEFAULT_HOSTNAME
    +  private var port: Int = 0
    +  private var maxThreads: Int = SparkSinkConfig.DEFAULT_MAX_THREADS
    +  private var serverOpt: Option[NettyServer] = None
    +  private var running = false
    +
    +  override def start() {
    +    transactionExecutorOpt = Option(Executors.newFixedThreadPool(numProcessors,
    +      new ThreadFactoryBuilder().setDaemon(true)
    +        .setNameFormat("Spark Sink, " + getName + " Processor Thread - %d").build()))
    +
    +    processorFactory = Option(new SparkHandlerFactory(numProcessors))
    +
    +    val responder = new SpecificResponder(classOf[SparkFlumeProtocol], new AvroCallbackHandler())
    +
    +    // Using the constructor that takes specific thread-pools requires bringing in netty
    +    // dependencies which are being excluded in the build. In practice,
    +    // Netty dependencies are already available on the JVM as Flume would have pulled them in.
    +    serverOpt = Option(new NettyServer(responder, new InetSocketAddress(hostname, port)))
    +
    +    serverOpt.map(server => server.start())
    +    lock.lock()
    +    try {
    +      running = true
    +    } finally {
    +      lock.unlock()
    +    }
    +    super.start()
    +  }
    +
    +  override def stop() {
    --- End diff --
    
    Shouldnt `super.stop()` be called as well?


---
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 infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] spark pull request: SPARK-1729. Make Flume pull data from source, ...

Posted by tdas <gi...@git.apache.org>.
Github user tdas commented on a diff in the pull request:

    https://github.com/apache/spark/pull/807#discussion_r13838534
  
    --- Diff: external/flume/src/main/scala/org/apache/spark/streaming/flume/FlumePollingInputDStream.scala ---
    @@ -0,0 +1,189 @@
    +/*
    + * 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.streaming.flume
    +
    +
    +import java.io.{ObjectOutput, ObjectInput, Externalizable}
    +import java.net.InetSocketAddress
    +import java.nio.ByteBuffer
    +import java.util.concurrent.{TimeUnit, Executors}
    +
    +import scala.collection.JavaConversions._
    +import scala.reflect.ClassTag
    +
    +import com.google.common.util.concurrent.ThreadFactoryBuilder
    +import org.apache.avro.ipc.NettyTransceiver
    +import org.apache.avro.ipc.specific.SpecificRequestor
    +import org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory
    +
    +import org.apache.spark.Logging
    +import org.apache.spark.flume.{SparkSinkEvent, SparkFlumeProtocol}
    +import org.apache.spark.storage.StorageLevel
    +import org.apache.spark.streaming.StreamingContext
    +import org.apache.spark.streaming.dstream.ReceiverInputDStream
    +import org.apache.spark.streaming.receiver.Receiver
    +
    +/**
    + * A [[ReceiverInputDStream]] that can be used to read data from several Flume agents running
    + * [[org.apache.spark.flume.sink.SparkSink]]s.
    + * @param ssc_ Streaming context that will execute this input stream
    + * @param addresses List of addresses at which SparkSinks are listening
    + * @param maxBatchSize Maximum size of a batch
    + * @param parallelism Number of parallel connections to open
    + * @param storageLevel The storage level to use.
    + * @tparam T Class type of the object of this stream
    + */
    +class FlumePollingInputDStream[T: ClassTag](
    +  @transient ssc_ : StreamingContext,
    +  val addresses: Seq[InetSocketAddress],
    +  val maxBatchSize: Int,
    +  val parallelism: Int,
    +  storageLevel: StorageLevel
    +) extends ReceiverInputDStream[SparkFlumePollingEvent](ssc_) {
    +  /**
    +   * Gets the receiver object that will be sent to the worker nodes
    +   * to receive data. This method needs to defined by any specific implementation
    +   * of a NetworkInputDStream.
    +   */
    +  override def getReceiver(): Receiver[SparkFlumePollingEvent] = {
    +    new FlumePollingReceiver(addresses, maxBatchSize, parallelism, storageLevel)
    +  }
    +}
    +
    +private[streaming] class FlumePollingReceiver(
    +  addresses: Seq[InetSocketAddress],
    +  maxBatchSize: Int,
    +  parallelism: Int,
    +  storageLevel: StorageLevel
    +) extends Receiver[SparkFlumePollingEvent](storageLevel) with Logging {
    +
    +  lazy val channelFactoryExecutor =
    +    Executors.newCachedThreadPool(new ThreadFactoryBuilder().setDaemon(true).
    +      setNameFormat("Flume Receiver Channel Thread - %d").build())
    +
    +  lazy val channelFactory =
    +    new NioClientSocketChannelFactory(channelFactoryExecutor, channelFactoryExecutor)
    +
    +  lazy val receiverExecutor = Executors.newFixedThreadPool(parallelism,
    +    new ThreadFactoryBuilder().setDaemon(true).setNameFormat("Flume Receiver Thread - %d").build())
    +
    +  private var connections = Array.empty[FlumeConnection] // temporarily empty, filled in later
    +
    +  override def onStart(): Unit = {
    +    // Create the connections to each Flume agent.
    +    connections = addresses.map(host => {
    +      val transceiver = new NettyTransceiver(host, channelFactory)
    +      val client = SpecificRequestor.getClient(classOf[SparkFlumeProtocol.Callback], transceiver)
    +      new FlumeConnection(transceiver, client)
    +    }).toArray
    +
    +    // Threads that pull data from Flume.
    +    val dataReceiver = new Runnable {
    +      override def run(): Unit = {
    +        var counter = 0
    +        while (true) {
    +          counter = counter % connections.size
    +          val client = connections(counter).client
    +          counter += 1
    +          val batch = client.getEventBatch(maxBatchSize)
    +          val seq = batch.getSequenceNumber
    +          val events: java.util.List[SparkSinkEvent] = batch.getEvents
    +          logDebug("Received batch of " + events.size() + " events with sequence number: " + seq)
    +          try {
    +            // Convert each Flume event to a serializable SparkPollingEvent
    +            events.foreach(event => {
    +              store(SparkFlumePollingEvent.fromSparkSinkEvent(event))
    +            })
    +            // Send an ack to Flume so that Flume discards the events from its channels.
    +            client.ack(seq)
    +          } catch {
    +            case e: Throwable =>
    +              try {
    +                // Let Flume know that the events need to be pushed back into the channel.
    +                client.nack(seq) // If the agent is down, even this could fail and throw
    +              } catch {
    +                case e: Throwable => logError("Sending Nack also failed. A Flume agent is down.")
    +              }
    --- End diff --
    
    same here, catch only exceptions.


---
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 infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] spark pull request: SPARK-1729. Make Flume pull data from source, ...

Posted by harishreedharan <gi...@git.apache.org>.
Github user harishreedharan commented on a diff in the pull request:

    https://github.com/apache/spark/pull/807#discussion_r13823899
  
    --- Diff: external/flume/src/main/scala/org/apache/spark/streaming/flume/EventTransformer.scala ---
    @@ -0,0 +1,72 @@
    +/*
    + * 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.streaming.flume
    +
    +import java.io.{ObjectOutput, ObjectInput}
    +
    +import scala.collection.JavaConversions._
    +
    +import org.apache.spark.util.Utils
    +import org.apache.spark.Logging
    +
    +/**
    + * A simple object that provides the implementation of readExternal and writeExternal for both
    + * the wrapper classes for Flume-style Events.
    + */
    +object EventTransformer extends Logging {
    +  def readExternal(in: ObjectInput): (java.util.HashMap[CharSequence, CharSequence],
    +    Array[Byte]) = {
    +    val bodyLength = in.readInt()
    +    val bodyBuff = new Array[Byte](bodyLength)
    +    in.read(bodyBuff)
    +
    +    val numHeaders = in.readInt()
    +    val headers = new java.util.HashMap[CharSequence, CharSequence]
    +
    +    for (i <- 0 until numHeaders) {
    +      val keyLength = in.readInt()
    +      val keyBuff = new Array[Byte](keyLength)
    +      in.read(keyBuff)
    +      val key: String = Utils.deserialize(keyBuff)
    +
    +      val valLength = in.readInt()
    +      val valBuff = new Array[Byte](valLength)
    +      in.read(valBuff)
    --- End diff --
    
    Same as above


---
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 infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] spark pull request: [STREAMING] SPARK-1729. Make Flume pull data f...

Posted by tdas <gi...@git.apache.org>.
Github user tdas commented on the pull request:

    https://github.com/apache/spark/pull/807#issuecomment-50400815
  
    Yeah, I will merge this as soon as this passes. 


---
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 infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] spark pull request: [STREAMING] SPARK-1729. Make Flume pull data f...

Posted by asfgit <gi...@git.apache.org>.
Github user asfgit closed the pull request at:

    https://github.com/apache/spark/pull/807


---
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 infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] spark pull request: SPARK-1729. Make Flume pull data from source, ...

Posted by SparkQA <gi...@git.apache.org>.
Github user SparkQA commented on the pull request:

    https://github.com/apache/spark/pull/807#issuecomment-49673590
  
    QA tests have started for PR 807. This patch merges cleanly. <br>View progress: https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/16932/consoleFull


---
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 infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] spark pull request: [STREAMING] SPARK-1729. Make Flume pull data f...

Posted by SparkQA <gi...@git.apache.org>.
Github user SparkQA commented on the pull request:

    https://github.com/apache/spark/pull/807#issuecomment-50419306
  
    QA tests have started for PR 807. This patch merges cleanly. <br>View progress: https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/17317/consoleFull


---
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 infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] spark pull request: SPARK-1729. Make Flume pull data from source, ...

Posted by tdas <gi...@git.apache.org>.
Github user tdas commented on a diff in the pull request:

    https://github.com/apache/spark/pull/807#discussion_r13466403
  
    --- Diff: external/flume-sink/src/main/scala/org/apache/spark/flume/sink/SparkSink.scala ---
    @@ -0,0 +1,392 @@
    +/*
    + * 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.flume.sink
    +
    +import org.apache.flume.sink.AbstractSink
    +import java.util.concurrent.locks.ReentrantLock
    +import org.apache.flume.Sink.Status
    +import org.apache.spark.flume.{SparkSinkEvent, EventBatch, SparkFlumeProtocol}
    +import scala.util.control.Breaks
    +import java.nio.ByteBuffer
    +import org.apache.flume.{FlumeException, Context}
    +import org.slf4j.LoggerFactory
    +import java.util.concurrent.atomic.AtomicLong
    +import org.apache.commons.lang.RandomStringUtils
    +import java.util.concurrent._
    +import java.util
    +import org.apache.flume.conf.{ConfigurationException, Configurable}
    +import com.google.common.util.concurrent.ThreadFactoryBuilder
    +import org.apache.avro.ipc.NettyServer
    +import org.apache.avro.ipc.specific.SpecificResponder
    +import java.net.InetSocketAddress
    +
    +class SparkSink() extends AbstractSink with Configurable {
    +  private val LOG = LoggerFactory.getLogger(this.getClass)
    +  private val lock = new ReentrantLock()
    +  private val blockingCondition = lock.newCondition()
    +
    +  // This sink will not persist sequence numbers and reuses them if it gets restarted.
    +  // So it is possible to commit a transaction which may have been meant for the sink before the
    +  // restart.
    +  // Since the new txn may not have the same sequence number we must guard against accidentally
    +  // committing
    +  // a new transaction. To reduce the probability of that happening a random string is prepended
    +  // to the sequence number.
    +  // Does not change for life of sink
    +  private val seqBase = RandomStringUtils.randomAlphanumeric(8)
    +  // Incremented for each transaction
    +  private val seqNum = new AtomicLong(0)
    +
    +  private var transactionExecutorOpt: Option[ExecutorService] = None
    +
    +  private var numProcessors: Integer = SparkSinkConfig.DEFAULT_PROCESSOR_COUNT
    +  private var transactionTimeout = SparkSinkConfig.DEFAULT_TRANSACTION_TIMEOUT
    +
    +  private val processorMap = new ConcurrentHashMap[CharSequence, TransactionProcessor]()
    +
    +  private var processorFactory: Option[SparkHandlerFactory] = None
    +  private var hostname: String = SparkSinkConfig.DEFAULT_HOSTNAME
    +  private var port: Int = 0
    +  private var maxThreads: Int = SparkSinkConfig.DEFAULT_MAX_THREADS
    +  private var serverOpt: Option[NettyServer] = None
    +  private var running = false
    +
    +  override def start() {
    +    transactionExecutorOpt = Option(Executors.newFixedThreadPool(numProcessors,
    +      new ThreadFactoryBuilder().setDaemon(true)
    +        .setNameFormat("Spark Sink, " + getName + " Processor Thread - %d").build()))
    +
    +    processorFactory = Option(new SparkHandlerFactory(numProcessors))
    +
    +    val responder = new SpecificResponder(classOf[SparkFlumeProtocol], new AvroCallbackHandler())
    +
    +    // Using the constructor that takes specific thread-pools requires bringing in netty
    +    // dependencies which are being excluded in the build. In practice,
    +    // Netty dependencies are already available on the JVM as Flume would have pulled them in.
    +    serverOpt = Option(new NettyServer(responder, new InetSocketAddress(hostname, port)))
    +
    +    serverOpt.map(server => server.start())
    +    lock.lock()
    +    try {
    +      running = true
    +    } finally {
    +      lock.unlock()
    +    }
    +    super.start()
    +  }
    +
    +  override def stop() {
    +    transactionExecutorOpt.map(executor => executor.shutdownNow())
    +    serverOpt.map(server => {
    +      server.close()
    +      server.join()
    +    })
    +    lock.lock()
    +    try {
    +      running = false
    +      blockingCondition.signalAll()
    +    } finally {
    +      lock.unlock()
    +    }
    +  }
    +
    +  override def configure(ctx: Context) {
    +    import SparkSinkConfig._
    +    hostname = ctx.getString(CONF_HOSTNAME, DEFAULT_HOSTNAME)
    +    val portOpt = Option(ctx.getInteger(CONF_PORT))
    +    if(portOpt.isDefined) {
    +      port = portOpt.get
    +    } else {
    +      throw new ConfigurationException("The Port to bind must be specified")
    +    }
    --- End diff --
    
    This can be written more concisely as 
    `port = Option(ctx.getInteger(CONF_PORT)).getOrElse { throw new ConfigurationException(...) }`


---
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 infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] spark pull request: [STREAMING] SPARK-1729. Make Flume pull data f...

Posted by SparkQA <gi...@git.apache.org>.
Github user SparkQA commented on the pull request:

    https://github.com/apache/spark/pull/807#issuecomment-50413968
  
    QA tests have started for PR 807. This patch merges cleanly. <br>View progress: https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/17313/consoleFull


---
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 infrastructure@apache.org or file a JIRA ticket
with INFRA.
---