save-buffer commented on code in PR #13669:
URL: https://github.com/apache/arrow/pull/13669#discussion_r972364563


##########
cpp/src/arrow/compute/exec/spilling_util.cc:
##########
@@ -0,0 +1,483 @@
+// 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.
+
+#include "spilling_util.h"
+#include <mutex>
+
+namespace arrow
+{
+namespace compute
+{
+    struct ArrayInfo
+    {
+        int64_t num_children;
+        int64_t length;
+        int64_t null_count;
+        std::shared_ptr<DataType> type;
+        std::array<std::shared_ptr<Buffer>, 3> bufs;
+        std::array<size_t, 3> sizes;
+        std::shared_ptr<ArrayData> dictionary;
+    };
+
+#ifdef _WIN32
+#include "windows_compatibility.h"
+
+    struct SpillFile::BatchInfo
+    {
+        int64_t start;
+        std::vector<ArrayInfo> arrays;
+    };
+
+const FileHandle kInvalidHandle = INVALID_HANDLE_VALUE;
+
+static Result<FileHandle> OpenTemporaryFile()
+{
+    constexpr DWORD kTempFileNameSize = MAX_PATH + 1;
+    wchar_t tmp_name_buf[kTempFileNameSize];
+    wchar_t tmp_path_buf[kTempFileNameSize];
+
+    DWORD ret;
+    ret = GetTempPath2W(kTempFileNameSize, tmp_path_buf);
+    if(ret > kTempFileNameSize || ret == 0)
+        return Status::IOError();
+    if(GetTempFileNameW(tmp_path_buf, L"ARROW_TMP", 0, tmp_name_buf) == 0)
+        return Status::IOError();
+
+    HANDLE file_handle = CreateFileA(
+        tmp_name_buf,
+        GENERIC_READ | GENERIC_WRITE | FILE_APPEND_DATA,
+        0,
+        NULL,
+        CREATE_ALWAYS,
+        FILE_FLAG_NO_BUFFERING | FILE_FLAG_OVERLAPPED | 
FILE_FLAG_DELETE_ON_CLOSE,
+        NULL);
+    if(file_handle == INVALID_HANDLE_VALUE)
+        return Status::IOError("Failed to create temp file");
+    return file_handle;
+}
+
+static Status CloseTemporaryFile(FileHandle handle)
+{
+    if(!CloseHandle(handle))
+        return Status::IOError("Failed to close temp file");
+    return Status::OK();
+}
+
+static Status WriteBatch_PlatformSpecific(FileHandle handle, const 
SpillFile::BatchInfo &info)
+{
+    OVERLAPPED overlapped;
+    int64_t offset = info.start;
+    for(const ArrayInfo &arr : info.arrays)
+    {
+        for(size_t i = 0; i < arr.bufs.size(); i++)
+        {
+            if(info.bufs[i] != 0)
+            {
+                overlapped.Offset = static_cast<DWORD>(offset & 
static_cast<DWORD>(~0));
+                overlapped.OffsetHigh = static_cast<DWORD>((offset >> 32) & 
static_cast<DWORD>(~0));
+                if(!WriteFile(
+                       handle,
+                       info.bufs[i]->data(),
+                       info.bufs[i]->size(),
+                       NULL,
+                       &overlapped))
+                    return Status::IOError("Failed to spill!");
+
+                offset += info.sizes[i];
+                info.bufs[i].reset();
+            }
+        }
+    }
+    return Status::OK();
+}
+
+
+static Result<std::shared_ptr<ArrayData>> ReconstructArray(
+    size_t &idx,
+    std::vector<ArrayInfo> &arrs,
+    size_t &current_offset)
+{
+    ArrayInfo &arr = arrs[idx++];
+    std::shared_ptr<ArrayData> data = std::make_shared<ArrayData>();
+    data->type = std::move(arr.type);
+    data->length = arr.length;
+    data->null_count = arr.null_count;
+    data->dictionary = std::move(arr.dictionary);
+
+    data->buffers.resize(3);
+    for(int i = 0; i < 3; i++)
+    {
+        if(arr.sizes[i])
+        {
+            data->buffers[i] = std::move(arr.bufs[i]);
+
+            OVERLAPPED overlapped;
+            overlapped.Offset = static_cast<DWORD>(current_offset & 
static_cast<DWORD>(~0));
+            overlapped.OffsetHigh = static_cast<DWORD>((current_offset >> 32) 
& static_cast<DWORD>(~0));
+            if(!ReadFile(
+                   handle,
+                   static_cast<void *>(data->buffers[i]->mutable_data()),
+                   arr.sizes[i],
+                   NULL,
+                   &overlapped))
+                return Status::IOError("Failed to read back spilled data!");
+            current_offset += arr.sizes[i];
+        }
+    }
+    data->child_data.resize(arr.num_children);
+    for(int i = 0; i < arr.num_children; i++)
+    {
+        ARROW_ASSIGN_OR_RAISE(data->child_data[i], ReconstructArray(idx, arrs, 
current_offset));
+    }
+
+    return data;
+}
+
+static Result<ExecBatch> ReadBatch_PlatformSpecific(
+    FileHandle handle,
+    SpillFile::BatchInfo &info)
+{
+    std::vector<Datum> batch;
+    size_t offset = info.start;
+    // ReconstructArray increments i
+    for(size_t i = 0; i < info.arrays.size();)
+    {
+        ARROW_ASSIGN_OR_RAISE(std::shared_ptr<ArrayData> ad, 
ReconstructArray(i, info.arrays, offset));
+        batch.emplace_back(std::move(ad));
+    }
+    return ExecBatch::Make(std::move(batch));
+}
+
+#else
+#include <sys/stat.h>
+#include <sys/types.h>
+#include <sys/uio.h>
+#include <unistd.h>
+#include <fcntl.h>
+
+    struct SpillFile::BatchInfo
+    {
+        int64_t start;
+        std::vector<ArrayInfo> arrays;
+        std::vector<struct iovec> ios;
+    };
+
+
+Result<FileHandle> OpenTemporaryFile()
+{
+    static std::once_flag generate_tmp_file_name_flag;
+
+    constexpr int kFileNameSize = 1024;
+    static char name_template[kFileNameSize];
+    char name[kFileNameSize];
+
+    char *name_template_ptr = name_template;
+    std::call_once(generate_tmp_file_name_flag, [name_template_ptr]() noexcept
+    {
+        const char *selectors[] = { "TMPDIR", "TMP", "TEMP", "TEMPDIR" };
+        constexpr size_t kNumSelectors = sizeof(selectors) / 
sizeof(selectors[0]);
+#ifdef __ANDROID__
+        const char *backup = "/data/local/tmp/";
+#else
+        const char *backup = "/var/tmp/";
+#endif
+        const char *tmp_dir = backup;
+        for(size_t i = 0; i < kNumSelectors; i++)
+        {
+            const char *env = getenv(selectors[i]);
+            if(env)
+            {
+                tmp_dir = env;
+                break;
+            }
+        }
+        size_t tmp_dir_length = std::strlen(tmp_dir);
+
+        const char *tmp_name_template = "/ARROW_TMP_XXXXXX";
+        size_t tmp_name_length = std::strlen(tmp_name_template);
+
+        if((tmp_dir_length + tmp_name_length) >= kFileNameSize)
+        {
+            tmp_dir = backup;
+            tmp_dir_length = std::strlen(backup);
+        }
+
+        std::strncpy(name_template_ptr, tmp_dir, kFileNameSize);
+        std::strncpy(name_template_ptr + tmp_dir_length, tmp_name_template, 
kFileNameSize - tmp_dir_length);
+    });
+
+    std::strncpy(name, name_template, kFileNameSize);
+
+#ifdef __APPLE__
+    int fd = mkstemp(name);
+    if(fd == kInvalidHandle)
+        return Status::IOError(strerror(errno));
+    if(fcntl(fd, F_NOCACHE, 1) == -1)
+        return Status::IOError(strerror(errno));
+#else
+    // If we failed, it's possible the temp directory didn't like O_DIRECT,
+    // so we try again without O_DIRECT, and if it still doesn't work then
+    // give up.
+    int fd = mkostemp(name, O_DIRECT);
+    if(fd == kInvalidHandle)
+    {
+        std::strncpy(name, name_template, kFileNameSize);
+        fd = mkstemp(name);
+        if(fd == kInvalidHandle)
+            return Status::IOError(strerror(errno));
+    }
+#endif
+
+    if(unlink(name) != 0)
+        return Status::IOError(strerror(errno));
+    return fd;
+}
+
+static Status CloseTemporaryFile(FileHandle handle)
+{
+    if(close(handle) == -1)
+        return Status::IOError(strerror(errno));
+    return Status::OK();
+}
+
+static Status WriteBatch_PlatformSpecific(FileHandle handle, 
SpillFile::BatchInfo &info)
+{
+    if(pwritev(handle, info.ios.data(), static_cast<int>(info.ios.size()), 
info.start) == -1)
+        return Status::IOError("Failed to spill!");
+
+    // Release all references to the buffers, freeing them. 
+    for(ArrayInfo &arr : info.arrays)
+        for(int i = 0; i < 3; i++)
+            if(arr.bufs[i])
+                arr.bufs[i].reset();
+    return Status::OK();
+}
+
+static Result<std::shared_ptr<ArrayData>> ReconstructArray(
+    size_t &idx,
+    SpillFile::BatchInfo &info)
+{
+    ArrayInfo &arr = info.arrays[idx++];
+    std::shared_ptr<ArrayData> data = std::make_shared<ArrayData>();
+    data->type = std::move(arr.type);
+    data->length = arr.length;
+    data->null_count = arr.null_count;
+    data->dictionary = std::move(arr.dictionary);
+    data->buffers.resize(3);
+    for(int i = 0; i < 3; i++)
+        if(arr.sizes[i])
+            data->buffers[i] = std::move(arr.bufs[i]);
+
+    data->child_data.resize(arr.num_children);
+    for(int i = 0; i < arr.num_children; i++)
+    {
+        ARROW_ASSIGN_OR_RAISE(data->child_data[i], ReconstructArray(idx, 
info));
+    }
+    return data;
+}
+
+static Result<ExecBatch> ReadBatch_PlatformSpecific(
+    FileHandle handle,
+    SpillFile::BatchInfo &info)
+{
+    std::vector<Datum> batch;
+    // ReconstructArray increments i
+    for(size_t i = 0; i < info.arrays.size();)
+    {
+        ARROW_ASSIGN_OR_RAISE(std::shared_ptr<ArrayData> ad, 
ReconstructArray(i, info));
+        batch.emplace_back(std::move(ad));
+    }
+
+    if(preadv(handle, info.ios.data(), static_cast<int>(info.ios.size()), 
info.start) == -1)
+        return Status::IOError(std::string("Failed to read back spilled data: 
") + std::strerror(errno));
+
+    return ExecBatch::Make(std::move(batch));
+}
+#endif
+
+    SpillFile::~SpillFile()
+    {
+        for(BatchInfo *b : batches_)

Review Comment:
   File gets deleted automatically when closed (it is `unlink`ed)



-- 
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: github-unsubscr...@arrow.apache.org

For queries about this service, please contact Infrastructure at:
us...@infra.apache.org

Reply via email to