hyperscaledesignhub commented on code in PR #8:
URL: https://github.com/apache/fluss-benchmarks/pull/8#discussion_r3412837474


##########
e2e-iot/fluss_flink_realtime/src/main/java/org/apache/fluss/benchmark/e2eplatformaws/producer/FlussSensorProducerAppMultiInstance.java:
##########
@@ -0,0 +1,545 @@
+/*
+ * 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.fluss.benchmark.e2eplatformaws.producer;
+
+import org.apache.fluss.benchmark.e2eplatformaws.model.SensorDataMinimal;
+import org.apache.fluss.client.Connection;
+import org.apache.fluss.client.ConnectionFactory;
+import org.apache.fluss.client.admin.Admin;
+import org.apache.fluss.client.table.Table;
+import org.apache.fluss.client.table.writer.UpsertWriter;
+import org.apache.fluss.config.ConfigOptions;
+import org.apache.fluss.config.Configuration;
+import org.apache.fluss.config.MemorySize;
+import org.apache.fluss.metadata.DatabaseDescriptor;
+import org.apache.fluss.metadata.Schema;
+import org.apache.fluss.metadata.TableDescriptor;
+import org.apache.fluss.metadata.TablePath;
+import org.apache.fluss.row.GenericRow;
+import org.apache.fluss.types.DataTypes;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.time.Duration;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+import java.util.Locale;
+import java.util.Random;
+import java.util.concurrent.*;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicLong;
+import java.util.concurrent.atomic.LongAdder;
+
+/**
+ * Multi-instance Fluss producer that supports distributed device generation 
across multiple producer instances.
+ * 
+ * Features:
+ * - Supports 100,000 devices total, distributed across multiple producer 
instances
+ * - Each instance handles a specific device ID range based on instance-id and 
total-producers
+ * - Multiple threads write in parallel to maximize throughput
+ * - Each device has its own generator with independent state
+ * - Device IDs are hashed to 48 buckets automatically by Fluss (via sensor_id 
hash)
+ * - Rate is distributed evenly across all devices in the instance's range
+ */
+public final class FlussSensorProducerAppMultiInstance {
+    private static final Logger LOG = 
LoggerFactory.getLogger(FlussSensorProducerAppMultiInstance.class);
+    
+    // Total number of devices across all producer instances
+    private static final int TOTAL_DEVICES = 100_000;
+
+    // Set IPv4-only properties in static initializer to ensure they're set 
before any class loading
+    static {
+        System.setProperty("java.net.preferIPv4Stack", "true");
+        System.setProperty("java.net.preferIPv4Addresses", "true");
+        System.setProperty("java.net.useSystemProxies", "false");
+    }
+
+    public static void main(String[] args) throws Exception {
+        // Ensure IPv4 properties are set (redundant but safe)
+        System.setProperty("java.net.preferIPv4Stack", "true");
+        System.setProperty("java.net.preferIPv4Addresses", "true");
+        
+        ProducerOptions options = ProducerOptions.parse(args);
+        LOG.info("Starting multi-instance Fluss producer with options: {}", 
options);
+        
+        // Validate instance configuration
+        if (options.totalProducers <= 0) {
+            throw new IllegalArgumentException("total-producers must be > 0");
+        }
+        if (options.instanceId < 0 || options.instanceId >= 
options.totalProducers) {
+            throw new IllegalArgumentException(
+                    String.format("instance-id must be >= 0 and < 
total-producers (%d)", options.totalProducers));
+        }
+
+        // Calculate device ID range for this instance
+        int devicesPerInstance = TOTAL_DEVICES / options.totalProducers;
+        int startDeviceId = options.instanceId * devicesPerInstance;
+        int endDeviceId = (options.instanceId == options.totalProducers - 1) 
+                ? TOTAL_DEVICES  // Last instance gets any remainder
+                : (options.instanceId + 1) * devicesPerInstance;
+        int deviceCount = endDeviceId - startDeviceId;
+        
+        LOG.info("Instance {} of {}: Handling devices {} to {} ({} devices)", 
+                options.instanceId, options.totalProducers, startDeviceId, 
endDeviceId - 1, deviceCount);
+
+        Configuration flussConf = new Configuration();
+        flussConf.set(ConfigOptions.BOOTSTRAP_SERVERS, 
Collections.singletonList(options.bootstrap));
+        flussConf.set(ConfigOptions.CLIENT_WRITER_BUFFER_MEMORY_SIZE, 
options.writerBufferSize);
+        flussConf.set(ConfigOptions.CLIENT_WRITER_BATCH_SIZE, 
options.writerBatchSize);
+        // Set batch timeout from environment variable (default: 50ms for 
optimal throughput)
+        String batchTimeoutStr = getEnv("CLIENT_WRITER_BATCH_TIMEOUT", "50ms");
+        try {
+            // Parse duration string like "10ms", "50ms", etc.
+            long millis = Long.parseLong(batchTimeoutStr.replaceAll("[^0-9]", 
""));
+            flussConf.set(ConfigOptions.CLIENT_WRITER_BATCH_TIMEOUT, 
Duration.ofMillis(millis));
+            LOG.info("Set CLIENT_WRITER_BATCH_TIMEOUT to {}ms", millis);
+        } catch (Exception e) {
+            LOG.warn("Failed to parse CLIENT_WRITER_BATCH_TIMEOUT '{}', using 
default 50ms", batchTimeoutStr);
+            flussConf.set(ConfigOptions.CLIENT_WRITER_BATCH_TIMEOUT, 
Duration.ofMillis(50));
+        }
+
+        
+        // Start Prometheus metrics server
+        ProducerMetrics metrics = new ProducerMetrics(8080);
+        metrics.start();
+        LOG.info("Prometheus metrics server started on port 8080");
+
+        TablePath tablePath = TablePath.of(options.database, options.table);
+
+        try (Connection connection = 
ConnectionFactory.createConnection(flussConf)) {
+            ensureSchema(connection, tablePath, options.bucketCount);
+
+            try (Table table = connection.getTable(tablePath)) {
+                AtomicBoolean running = new AtomicBoolean(true);
+                Runtime.getRuntime()
+                        .addShutdownHook(new Thread(() -> shutdown(running), 
"fluss-producer-shutdown"));
+
+                // Create thread pool for parallel writing
+                int numThreads = options.numWriterThreads;
+                ExecutorService executor = 
Executors.newFixedThreadPool(numThreads);
+                CountDownLatch completionLatch = new 
CountDownLatch(numThreads);
+                
+                // Shared counters for statistics
+                LongAdder totalSent = new LongAdder();
+                AtomicLong startNano = new AtomicLong(System.nanoTime());
+                AtomicLong lastStatsNano = new AtomicLong(startNano.get());
+                
+                // Rate control: distribute rate across threads
+                // Each thread should produce: totalRate / numThreads records 
per second
+                double ratePerThread = options.recordsPerSecond > 0 
+                        ? (double) options.recordsPerSecond / numThreads 
+                        : 0.0;
+                long nanosPerRecordPerThread = ratePerThread > 0 
+                        ? (long) (TimeUnit.SECONDS.toNanos(1) / ratePerThread)
+                        : 0;
+                
+                LOG.info("Target rate: {} rec/s total, {} rec/s per thread, {} 
writer threads", 
+                        options.recordsPerSecond, String.format(Locale.ROOT, 
"%.2f", ratePerThread), numThreads);
+
+                // Divide devices among threads
+                int devicesPerThread = (deviceCount + numThreads - 1) / 
numThreads; // Ceiling division
+                
+                // Start writer threads
+                for (int threadId = 0; threadId < numThreads; threadId++) {
+                    int threadStartDevice = startDeviceId + threadId * 
devicesPerThread;
+                    int threadEndDevice = Math.min(threadStartDevice + 
devicesPerThread, endDeviceId);
+                    
+                    if (threadStartDevice >= endDeviceId) {
+                        // No devices for this thread
+                        completionLatch.countDown();
+                        continue;
+                    }
+                    
+                    final int finalThreadId = threadId;
+                    final int finalThreadStartDevice = threadStartDevice;
+                    final int finalThreadEndDevice = threadEndDevice;
+                    
+                    executor.submit(() -> {
+                        try {
+                            UpsertWriter writer = 
table.newUpsert().createWriter();
+                            DeviceRangeGenerator generator = new 
DeviceRangeGenerator(
+                                    finalThreadStartDevice, 
+                                    finalThreadEndDevice);
+                            
+                            long threadSent = 0;
+                            long threadStartNano = System.nanoTime();
+                            long stopAtCount = options.totalRecords > 0 ? 
options.totalRecords : Long.MAX_VALUE;
+                            long stopAtTime = options.runDuration.isZero()
+                                    ? Long.MAX_VALUE
+                                    : System.nanoTime() + 
options.runDuration.toNanos();
+                            
+                            LOG.info("[Thread {}] Starting - will stop at {} 
total records", finalThreadId, stopAtCount);
+                            
+                            while (running.get() && totalSent.sum() < 
stopAtCount && System.nanoTime() < stopAtTime) {
+                                SensorDataMinimal record = generator.next();
+                                writeToFluss(writer, record);
+                                threadSent++;
+                                totalSent.increment();
+                                long currentTotal = totalSent.sum();
+                                metrics.recordWrite();
+                                
+                                if (currentTotal % 10 == 0) {

Review Comment:
   Changed the logging to interval based logging. Where we supply required 
interval value externally. 



-- 
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.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to