rpuch commented on code in PR #2390:
URL: https://github.com/apache/ignite-3/pull/2390#discussion_r1286667487


##########
modules/file-transfer/src/main/java/org/apache/ignite/internal/network/file/ChunkedFileWriter.java:
##########
@@ -0,0 +1,69 @@
+/*
+ * 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.ignite.internal.network.file;
+
+import java.io.FileNotFoundException;
+import java.io.IOException;
+import java.io.RandomAccessFile;
+import java.nio.file.Path;
+import java.util.PriorityQueue;
+import java.util.Queue;
+import org.apache.ignite.internal.close.ManuallyCloseable;
+import org.apache.ignite.internal.network.file.messages.FileChunkMessage;
+
+class ChunkedFileWriter implements ManuallyCloseable {
+    private final RandomAccessFile raf;
+
+    private long fileSize;
+
+    private final Queue<FileChunkMessage> chunks = new 
PriorityQueue<>(FileChunkMessage.COMPARATOR);
+
+    private ChunkedFileWriter(RandomAccessFile raf, long fileSize) {
+        this.raf = raf;
+        this.fileSize = fileSize;
+    }
+
+    static ChunkedFileWriter open(Path path, long fileSize) throws 
FileNotFoundException {
+        return new ChunkedFileWriter(new RandomAccessFile(path.toFile(), 
"rw"), fileSize);
+    }
+
+    void write(FileChunkMessage chunk) throws IOException {
+        chunks.add(chunk);
+
+        while (!chunks.isEmpty() && chunks.peek().offset() == 
raf.getFilePointer()) {

Review Comment:
   Why is this queue needed? Can the chunks be written out-of-order?



##########
modules/file-transfer/src/main/java/org/apache/ignite/internal/network/file/FileTransferMessagesHandler.java:
##########
@@ -0,0 +1,171 @@
+/*
+ * 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.ignite.internal.network.file;
+
+import java.io.File;
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.concurrent.locks.Lock;
+import java.util.concurrent.locks.ReentrantLock;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
+import org.apache.ignite.internal.network.file.messages.FileChunkMessage;
+import org.apache.ignite.internal.network.file.messages.FileHeaderMessage;
+import 
org.apache.ignite.internal.network.file.messages.FileTransferInfoMessage;
+import org.apache.ignite.internal.util.IgniteUtils;
+import org.apache.ignite.lang.IgniteInternalException;
+
+class FileTransferMessagesHandler {
+    private final Path dir;
+    private final AtomicInteger filesCount = new AtomicInteger(-1);
+    private final AtomicInteger filesFinished = new AtomicInteger(0);
+    private final CompletableFuture<List<File>> result = new 
CompletableFuture<>();
+    private final Map<String, ChunkedFileWriter> fileNameToWriter = new 
ConcurrentHashMap<>();
+    private final Map<String, Lock> fileNameToLock = new ConcurrentHashMap<>();
+
+    FileTransferMessagesHandler(Path dir) {
+        this.dir = dir;
+    }
+
+    void handleFileTransferInfo(FileTransferInfoMessage info) {
+        if (result.isDone()) {
+            throw new IllegalStateException("Received file transfer info after 
result is already done.");
+        }
+
+        filesCount.set(info.filesCount());
+
+        try {
+            completeIfAllFilesFinished();
+        } catch (IOException e) {
+            handleFileTransferError(e);
+        }
+    }
+
+    void handleFileHeader(FileHeaderMessage header) {
+        if (result.isDone()) {
+            throw new IllegalStateException("Received file header after result 
is already done.");
+        }
+        doInLock(header.fileName(), () -> handleFileHeader0(header));
+    }
+
+    private void handleFileHeader0(FileHeaderMessage header) {
+        ChunkedFileWriter writer = fileNameToWriter.compute(header.fileName(), 
(k, v) -> {
+            if (v == null) {
+                return writer(header.fileName(), header.fileSize());
+            } else {
+                v.fileSize(header.fileSize());
+                return v;
+            }
+        });
+
+        try {
+            if (writer.isFinished()) {
+                writer.close();
+                filesFinished.incrementAndGet();
+                completeIfAllFilesFinished();
+            }
+        } catch (IOException e) {
+            handleFileTransferError(e);
+        }
+    }
+
+    void handleFileChunk(FileChunkMessage fileChunk) {
+        if (result.isDone()) {
+            throw new IllegalStateException("Received chunked file after 
result is already done.");
+        }
+        doInLock(fileChunk.fileName(), () -> handleFileChunk0(fileChunk));

Review Comment:
   This is called from a network thread. No blocking/IO operations should be 
run on this thread



##########
modules/network/src/main/java/org/apache/ignite/internal/network/configuration/NetworkConfigurationSchema.java:
##########
@@ -78,4 +78,8 @@ public class NetworkConfigurationSchema {
     @ConfigValue
     @SslConfigurationValidator
     public SslConfigurationSchema ssl;
+
+    /** File transferring configuration. */
+    @ConfigValue
+    public FileTransferConfigurationSchema fileTransferring;

Review Comment:
   ```suggestion
       public FileTransferConfigurationSchema fileTransfer;
   ```



##########
modules/file-transfer/src/testFixtures/java/org/apache/ignite/internal/network/file/FileUtils.java:
##########
@@ -0,0 +1,44 @@
+/*
+ * 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.ignite.internal.network.file;
+
+import java.io.File;
+import java.util.Comparator;
+import java.util.List;
+import java.util.stream.Collectors;
+
+/**
+ * File utils.
+ */
+public class FileUtils {
+    public static List<File> sortByNames(File... files) {
+        return sortByNames(List.of(files));
+    }
+
+    /**
+     * Sorts files by names.
+     *
+     * @param files Files.
+     * @return Sorted files.
+     */
+    public static List<File> sortByNames(List<File> files) {
+        return files.stream()
+                .sorted(Comparator.comparing(File::getName))
+                .collect(Collectors.toList());

Review Comment:
   Let's import `toList()` statically, this would make the line read as an 
English phrase



##########
modules/core/src/main/java/org/apache/ignite/internal/util/FilesUtils.java:
##########
@@ -0,0 +1,60 @@
+/*
+ * 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.ignite.internal.util;
+
+import java.io.IOException;
+import java.nio.file.FileVisitResult;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.SimpleFileVisitor;
+import java.nio.file.attribute.BasicFileAttributes;
+
+/**
+ * Files utilities.
+ */
+public class FilesUtils {

Review Comment:
   It looks like there are not tests for this class. Let's add them.



##########
modules/file-transfer/src/main/java/org/apache/ignite/internal/network/file/FileSender.java:
##########
@@ -0,0 +1,114 @@
+/*
+ * 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.ignite.internal.network.file;
+
+import java.io.File;
+import java.io.IOException;
+import java.util.List;
+import java.util.UUID;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.LinkedBlockingQueue;
+import java.util.concurrent.ThreadPoolExecutor;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicReference;
+import java.util.function.BiFunction;
+import org.apache.ignite.internal.logger.IgniteLogger;
+import org.apache.ignite.internal.logger.Loggers;
+import org.apache.ignite.internal.thread.NamedThreadFactory;
+import org.apache.ignite.internal.util.IgniteUtils;
+import org.apache.ignite.network.NetworkMessage;
+
+class FileSender {
+    private static final IgniteLogger LOG = Loggers.forClass(FileSender.class);
+
+    private final int chunkSize;
+
+    private final RateLimiter rateLimiter;
+
+    private final BiFunction<String, NetworkMessage, CompletableFuture<Void>> 
send;
+
+    private final ExecutorService executorService;
+
+    FileSender(
+            String nodeName,
+            int chunkSize,
+            int threadPoolSize,
+            RateLimiter rateLimiter,
+            BiFunction<String, NetworkMessage, CompletableFuture<Void>> send) {
+        this.send = send;
+        this.chunkSize = chunkSize;
+        this.rateLimiter = rateLimiter;
+        this.executorService = new ThreadPoolExecutor(
+                0,
+                threadPoolSize,
+                0L, TimeUnit.MILLISECONDS,
+                new LinkedBlockingQueue<Runnable>(),
+                NamedThreadFactory.create(nodeName, "file-sender", LOG)
+        );
+    }
+
+    /**
+     * Adds files to the queue to be sent to the receiver.
+     */
+    CompletableFuture<Void> send(String receiverConsistentId, UUID id, 
List<File> files) {
+        return CompletableFuture.runAsync(() -> send0(receiverConsistentId, 
id, files), executorService);
+    }
+
+    private void send0(String receiverConsistentId, UUID id, List<File> files) 
{
+        AtomicReference<Throwable> error = new AtomicReference<>();
+        try (FileTransferMessagesStream stream = new 
FileTransferMessagesStream(id, files, chunkSize)) {
+            while (stream.hasNextMessage() && error.get() == null && 
!Thread.currentThread().isInterrupted()) {
+                if (rateLimiter.tryAcquire()) {
+                    CompletableFuture.completedFuture(stream.nextMessage())
+                            .thenCompose(message -> 
send.apply(receiverConsistentId, message))
+                            .whenComplete((res, e) -> {
+                                try {
+                                    if (e != null) {
+                                        LOG.error("Failed to send message to 
node: {}, transfer id: {}. Exception: {}",
+                                                receiverConsistentId,
+                                                id,
+                                                e
+                                        );
+                                        error.compareAndSet(null, e);
+                                    }
+                                } finally {
+                                    rateLimiter.release();
+                                }
+                            });
+                }
+            }
+
+            if (error.get() != null) {

Review Comment:
   Do we wait for the sends to complete somewhere? If not, we'll probably miss 
an error if it happens



##########
modules/file-transfer/src/main/java/org/apache/ignite/internal/network/file/FileSender.java:
##########
@@ -0,0 +1,114 @@
+/*
+ * 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.ignite.internal.network.file;
+
+import java.io.File;
+import java.io.IOException;
+import java.util.List;
+import java.util.UUID;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.LinkedBlockingQueue;
+import java.util.concurrent.ThreadPoolExecutor;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicReference;
+import java.util.function.BiFunction;
+import org.apache.ignite.internal.logger.IgniteLogger;
+import org.apache.ignite.internal.logger.Loggers;
+import org.apache.ignite.internal.thread.NamedThreadFactory;
+import org.apache.ignite.internal.util.IgniteUtils;
+import org.apache.ignite.network.NetworkMessage;
+
+class FileSender {
+    private static final IgniteLogger LOG = Loggers.forClass(FileSender.class);
+
+    private final int chunkSize;
+
+    private final RateLimiter rateLimiter;
+
+    private final BiFunction<String, NetworkMessage, CompletableFuture<Void>> 
send;
+
+    private final ExecutorService executorService;
+
+    FileSender(
+            String nodeName,
+            int chunkSize,
+            int threadPoolSize,
+            RateLimiter rateLimiter,
+            BiFunction<String, NetworkMessage, CompletableFuture<Void>> send) {
+        this.send = send;
+        this.chunkSize = chunkSize;
+        this.rateLimiter = rateLimiter;
+        this.executorService = new ThreadPoolExecutor(
+                0,
+                threadPoolSize,
+                0L, TimeUnit.MILLISECONDS,
+                new LinkedBlockingQueue<Runnable>(),
+                NamedThreadFactory.create(nodeName, "file-sender", LOG)
+        );
+    }
+
+    /**
+     * Adds files to the queue to be sent to the receiver.
+     */
+    CompletableFuture<Void> send(String receiverConsistentId, UUID id, 
List<File> files) {
+        return CompletableFuture.runAsync(() -> send0(receiverConsistentId, 
id, files), executorService);
+    }
+
+    private void send0(String receiverConsistentId, UUID id, List<File> files) 
{
+        AtomicReference<Throwable> error = new AtomicReference<>();
+        try (FileTransferMessagesStream stream = new 
FileTransferMessagesStream(id, files, chunkSize)) {
+            while (stream.hasNextMessage() && error.get() == null && 
!Thread.currentThread().isInterrupted()) {
+                if (rateLimiter.tryAcquire()) {
+                    CompletableFuture.completedFuture(stream.nextMessage())
+                            .thenCompose(message -> 
send.apply(receiverConsistentId, message))
+                            .whenComplete((res, e) -> {
+                                try {
+                                    if (e != null) {
+                                        LOG.error("Failed to send message to 
node: {}, transfer id: {}. Exception: {}",

Review Comment:
   Let's use another variant of `IgniteLogger.error()`: the one that takes a 
Throwable as a second argument. Then the exception does not need to be 
mentioned explicitly in the log message.



##########
modules/file-transfer/src/main/java/org/apache/ignite/internal/network/file/ChunkedFileWriter.java:
##########
@@ -0,0 +1,69 @@
+/*
+ * 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.ignite.internal.network.file;
+
+import java.io.FileNotFoundException;
+import java.io.IOException;
+import java.io.RandomAccessFile;
+import java.nio.file.Path;
+import java.util.PriorityQueue;
+import java.util.Queue;
+import org.apache.ignite.internal.close.ManuallyCloseable;
+import org.apache.ignite.internal.network.file.messages.FileChunkMessage;
+
+class ChunkedFileWriter implements ManuallyCloseable {
+    private final RandomAccessFile raf;
+
+    private long fileSize;
+
+    private final Queue<FileChunkMessage> chunks = new 
PriorityQueue<>(FileChunkMessage.COMPARATOR);

Review Comment:
   `PriorityQueue` is not thread-safe. If there a guarantee that the queue is 
always accessed from the same thread?



##########
modules/file-transfer/src/main/java/org/apache/ignite/internal/network/file/FileTransferMessagesHandler.java:
##########
@@ -0,0 +1,171 @@
+/*
+ * 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.ignite.internal.network.file;
+
+import java.io.File;
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.concurrent.locks.Lock;
+import java.util.concurrent.locks.ReentrantLock;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
+import org.apache.ignite.internal.network.file.messages.FileChunkMessage;
+import org.apache.ignite.internal.network.file.messages.FileHeaderMessage;
+import 
org.apache.ignite.internal.network.file.messages.FileTransferInfoMessage;
+import org.apache.ignite.internal.util.IgniteUtils;
+import org.apache.ignite.lang.IgniteInternalException;
+
+class FileTransferMessagesHandler {
+    private final Path dir;
+    private final AtomicInteger filesCount = new AtomicInteger(-1);
+    private final AtomicInteger filesFinished = new AtomicInteger(0);
+    private final CompletableFuture<List<File>> result = new 
CompletableFuture<>();
+    private final Map<String, ChunkedFileWriter> fileNameToWriter = new 
ConcurrentHashMap<>();
+    private final Map<String, Lock> fileNameToLock = new ConcurrentHashMap<>();
+
+    FileTransferMessagesHandler(Path dir) {
+        this.dir = dir;
+    }
+
+    void handleFileTransferInfo(FileTransferInfoMessage info) {
+        if (result.isDone()) {
+            throw new IllegalStateException("Received file transfer info after 
result is already done.");
+        }
+
+        filesCount.set(info.filesCount());
+
+        try {
+            completeIfAllFilesFinished();
+        } catch (IOException e) {
+            handleFileTransferError(e);
+        }
+    }
+
+    void handleFileHeader(FileHeaderMessage header) {
+        if (result.isDone()) {
+            throw new IllegalStateException("Received file header after result 
is already done.");
+        }
+        doInLock(header.fileName(), () -> handleFileHeader0(header));

Review Comment:
   This is called from a network thread. No blocking/IO operations should be 
run on this thread



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