[ 
https://issues.apache.org/jira/browse/BEAM-7896?focusedWorklogId=291554&page=com.atlassian.jira.plugin.system.issuetabpanels:worklog-tabpanel#worklog-291554
 ]

ASF GitHub Bot logged work on BEAM-7896:
----------------------------------------

                Author: ASF GitHub Bot
            Created on: 08/Aug/19 20:04
            Start Date: 08/Aug/19 20:04
    Worklog Time Spent: 10m 
      Work Description: akedin commented on pull request #9298: [BEAM-7896] 
Implementing RateEstimation for KafkaTable 
URL: https://github.com/apache/beam/pull/9298#discussion_r312219083
 
 

 ##########
 File path: 
sdks/java/extensions/sql/src/main/java/org/apache/beam/sdk/extensions/sql/meta/provider/kafka/BeamKafkaTable.java
 ##########
 @@ -138,6 +161,96 @@ public String getBootstrapServers() {
 
   @Override
   public BeamTableStatistics getTableStatistics(PipelineOptions options) {
-    return BeamTableStatistics.UNBOUNDED_UNKNOWN;
+    if (rowCountStatistics == null) {
+      try {
+        rowCountStatistics =
+            BeamTableStatistics.createUnboundedTableStatistics(
+                this.computeRate(numberOfRecordsForRate));
+      } catch (Exception e) {
+        LOGGER.warn("Could not get the row count for the topics " + 
getTopics(), e);
+        rowCountStatistics = BeamTableStatistics.UNBOUNDED_UNKNOWN;
+      }
+    }
+
+    return rowCountStatistics;
+  }
+
+  /**
+   * This method returns the estimate of the computeRate for this table using 
last numberOfRecords
+   * tuples in each partition.
+   */
+  double computeRate(int numberOfRecords) throws NoEstimationException {
+    Properties props = new Properties();
+
+    props.put("bootstrap.servers", bootstrapServers);
+    props.put("session.timeout.ms", "30000");
+    props.put("key.deserializer", 
"org.apache.kafka.common.serialization.StringDeserializer");
+    props.put("value.deserializer", 
"org.apache.kafka.common.serialization.StringDeserializer");
+
+    KafkaConsumer<String, String> consumer = new KafkaConsumer<String, 
String>(props);
+
+    return computeRate(consumer, numberOfRecords);
+  }
+
+  double computeRate(Consumer consumer, int numberOfRecordsToCheck) throws 
NoEstimationException {
+
+    List<TopicPartition> topars = new ArrayList<>();
+    for (String name : getTopics()) {
+      List<PartitionInfo> parInfList = consumer.partitionsFor(name);
+      topars.addAll(
+          parInfList.stream()
+              .map(parInf -> new TopicPartition(name, parInf.partition()))
+              .collect(Collectors.toList()));
+    }
+
+    consumer.assign(topars);
+    Map<TopicPartition, Long> offsets = consumer.endOffsets(topars);
+    long nParsSeen = 0;
+    for (TopicPartition par : topars) {
+      long offset = offsets.get(par);
+      nParsSeen = (offset == 0) ? nParsSeen : nParsSeen + 1;
+      consumer.seek(par, Math.max(0L, offset - numberOfRecordsToCheck));
+    }
+
+    if (nParsSeen == 0) {
+      throw new NoEstimationException("There is no partition with messages in 
it.");
+    }
+
+    ConsumerRecords<String, String> records = consumer.poll(1000);
+
+    Map<Integer, Long> minTimeStamps = new HashMap<>();
+    long maxMinTimeStamp = 0;
+    for (ConsumerRecord<String, String> record : records) {
+      if (!minTimeStamps.containsKey(record.partition())) {
+        minTimeStamps.put(record.partition(), record.timestamp());
+
+        nParsSeen--;
+        maxMinTimeStamp = Math.max(record.timestamp(), maxMinTimeStamp);
+        if (nParsSeen == 0) {
+          break;
+        }
+      }
+    }
+
+    int numberOfRecords = 0;
+    long maxTimeStamp = 0;
+    for (ConsumerRecord<String, String> record : records) {
+      maxTimeStamp = Math.max(maxTimeStamp, record.timestamp());
+      numberOfRecords =
+          record.timestamp() > maxMinTimeStamp ? numberOfRecords + 1 : 
numberOfRecords;
+    }
+
+    if (maxTimeStamp == maxMinTimeStamp) {
+      throw new NoEstimationException("Arrival time of all records are the 
same.");
+    }
+
+    return (numberOfRecords * 1000.) / ((double) maxTimeStamp - 
maxMinTimeStamp);
+  }
+
+  /** Will be thrown if we cannot estimate the rate for kafka table. */
+  public static class NoEstimationException extends Exception {
 
 Review comment:
   Can be package private?
 
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
 
For queries about this service, please contact Infrastructure at:
[email protected]


Issue Time Tracking
-------------------

    Worklog Id:     (was: 291554)
    Time Spent: 1h 40m  (was: 1.5h)

> Rate estimation for Kafka Table
> -------------------------------
>
>                 Key: BEAM-7896
>                 URL: https://issues.apache.org/jira/browse/BEAM-7896
>             Project: Beam
>          Issue Type: New Feature
>          Components: dsl-sql
>            Reporter: Alireza Samadianzakaria
>            Assignee: Alireza Samadianzakaria
>            Priority: Major
>          Time Spent: 1h 40m
>  Remaining Estimate: 0h
>
> Currently, KafkaTable returns UNKNOWN statistics for its rate. 
> We can use previously arrived tuples to estimate the rate and return correct 
> statistics (See 
> [https://docs.google.com/document/d/1vi1PBBu5IqSy-qZl1Gk-49CcANOpbNs1UAud6LnOaiY|https://docs.google.com/document/d/1vi1PBBu5IqSy-qZl1Gk-49CcANOpbNs1UAud6LnOaiY/])
>  



--
This message was sent by Atlassian JIRA
(v7.6.14#76016)

Reply via email to